How to: dynamically add input field in form, using Javascript

Recently I ran across this issue on a project. Whereas I need to employ a html textarea when needed (dynamic), plus the delete link.

These is the Javascript part:
function addElement(fieldType, fieldName, className, ctrl1, ctrl2) {
var ni = document.getElementById(ctrl1);
var numi = document.getElementById(ctrl2);
var num = (document.getElementById(ctrl2).value -1)+ 2;
numi.value = num;
var divIdName = ctrl1+num;
var newdiv = document.createElement('span');
newdiv.setAttribute("id",divIdName);
if (fieldType == 'textarea') {
newdiv.innerHTML = " [x]
";
} else if (fieldType == 'file') {
newdiv.innerHTML = " [x]
";
} else {
newdiv.innerHTML = " [x]
";
}
ni.appendChild(newdiv);
}

function removeElement(divNum, ctrl1) {
var d = document.getElementById(ctrl1);
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

Function addElement(fieldType, fieldName, className, ctrl1, ctrl2):
Available arguments:
[*]fieldType:
HTML field types, available: text (default), textarea and file (upload).
[*]fieldName:
Name of the field, this will make something like this:

[*]className:
HTML class, something like this:

[*]ctrl1:
Parent id, see sample below.
[*]ctrl2:
Child id, see sample below.

If you want to add textarea field with name “myTextarea”, class “textareaClass”, child id “theChild” and parent id “theParent”, it would be:
addElement('textarea', 'myTextarea', 'textareaClass', 'theChild', 'theParent')

And this is the html part:

[add field]

Live sample is >here.

Good luck!

Ref: Professional JavaScript for Web Developers (Wrox Programmer to Programmer)

No Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: