Dynamic Creation of Form Input Elements
Below is a list of the standard visible form input elements, created dynamically and with properties written with the setAttribute() method (1) or by direct manipulation of element properties (2). Click on any element for a list of the attributes assigned to it.
- Input type: text
- Input type: radio
- Input type: checkbox
- Input type: password
- Input type: submit
- Input type: reset
- Input type: file
- Input type: image
- Input type: button
How do these methods work?
Using the W3C DOM setArribute() method to create the text input:
var el = document.createElement('input');
el.setAttribute('type','text');
el.setAttribute('name','text1');
el.setAttribute('size','20');
el.setAttribute('value','text here');
document.getElementById('target').appendChild(el);
Direct manipulation of property values to create the same input element:
var el = document.createElement('input');
el.type = 'text';
el.name = 'text1';
el.size = '20';
el.value = 'text here';
document.getElementById('target').appendChild(el);
Codicil
Internet Explorer doesn't support setting the name attribute for dynamically-created elements (MSDN). A proprietary method must be used:
var obj = document.createElement('input');
obj.setAttribute('name','objname');
if (obj.getAttribute('name') != 'objname')
// browser does not support the W3C DOM method for assigning name attribute
{
obj = document.createElement('<input name="objname">');
}
// set other attributes ...