I got bit hard by this today:
function mk_input( name, val ) {
var inp = document.createElement( 'input' );
inp.name = name;
inp.value = val;
inp.type = 'hidden';
return inp;
}
As it turns out, setting the name
of an element created via createElement
doesn't work in IE. It doesn't cause an error or anything, it just silently fails, causing one to ponder why their hidden fields aren't getting populated correctly.
As far as I can tell, there's no workaround. You have to just bite the bullet and create the <input>
tag through string manipulation and stick it in with .innerHTML
instead.
Is there a better way? Perhaps with something like jQuery? I did a cursory search and didn't find anything exactly akin to createElement
in JQuery, but maybe I missed something.
They fixed this in IE8. In previous versions, you need to include the name when you call createElement. From MSDN:
Here is the example from MSDN:
Just to re-iterate the problem: in IE, programatically setting the
name
attribute on an element created viadocument.createElement('input')
is not reflected ingetElementsByName
,form.elements
(if appending to a form), and is not submitted with theform
(again, if appending to a form) [Reference].Here's the workaround I've used in the past (adapted to your question from here):
This is akin to feature detection (as opposed to browser detection). The first
createElement
will succeed in IE, while the latter will succeed in standards-compliant browsers.And of course the jQuery equivalent since you tagged the question as such:
(as a sidenote, under the hood jQuery is doing what you describe in your question: it creates a dummy
<div>
and sets itsinnerHTML
to the<input type="...
string passed above).As @jeffamaphone points out, this bug has been fixed in IE8.