06 Jul

IE bugs – dynamically creating form elements

I have a few scripts which have forms completely generated by JavaScript. In most browsers, this is fine, but IE, as usual, is “special”.

Look at this code:

var i=document.createElement('input');
i.name='action';
i.value='submit this form';
i.type='submit';

You would expect the above to provide something similar to this HTML:

<input type="submit" name="action" value="submit this form" >

Instead, the final line overwrites the values we’ve set and changes it to:

<input type="submit" name="action" value="Submit Query" >

That is annoying!

To work around that, make sure to set the type first.

var i=document.createElement('input');
i.type='submit';
i.name='action';
i.value='submit this form';

Another thing is multipart/form-data forms. With most browsers, you can create a form with the following code:

var form=document.createElement('form');
form.enctype='multipart/form-data';
form.action='shoppingcart_xhr.php';
form.method='POST';
form.target='shoppingcart_iframe';

The above code will mostly work in IE, except when you actually need to use the multipart aspect of it (uploading a file, for example), when it will barf.

In this case, IE seems to insist on the following crappy code:

form=document.createElement('<form action="shoppingcart_xhr.php" method="POST" enctype="multipart/form-data" target="shoppingcart_iframe">');

This is very annoying, and not friendly to my cross-browser sensibilities. But… at least it’s just the occasional form that needs that crap.