i have a script to create an input box, but i need to name it
dynamically suffixing the field with a loop counter (e.g. "field" +
x_counter). i've tried this a few ways unsucessfully. i even tried
creating a variable first and then setting the name property of the
input tag to equal the variable. no dice. ideas?
I guess you are referring to IE's problem with the name attribute when
adding form controls with script. If you add a control using
createElement and set the name attribute using either dot property or
setAttribute (which itself is broken in places in IE), you can't
access the element by name.
However, it will still be successful when you submit the form, you
just can't use document.forms.elementName (or similar) to access it.
One solution is to add an ID that is the same as the name, then
document.forms.elementNameID works fine. Another is to use innerHTML
to insert your new element into a div, then grab it and add it to the
form. A third is to use an entirely different ID and use
getElementById to access it.
Some play code:
<script type="text/javascript">
function addInputDOM(f) {
var el = document.createElement('input');
el.type = 'text';
el.value = 'fred';
el.name = 'text01';
/* Adding an ID the same as the name makes
** document.forms.text01 'work' in IE
*/
// el.id = 'text01';
f.appendChild(el);
}
function addInputHTML(f) {
var el = document.createElement('div');
el.innerHTML = '<input type=\'text\'' +
' value=\'fred\' name=\'text01\'>';
f.appendChild(el.firstChild);
}
</script>
</head>
<body>
<form>
<div>
<input type="button" value="DOM add field"
onclick="addInputDOM(this.form)">
<input type="button" value="innerHTML add field"
onclick="addInputHTML(this.form);">
<input type="button" value="Check name"
onclick="alert(typeof this.form.elements['text01']);">
<input type="submit"><br>
</div>
</form>