PDA

View Full Version : Dynamically adding form fields.


DanielJamesAtCo
07-23-2008, 03:25 PM
Ok, I hope I'm not reinventing the wheel here so to speak. Hopefully someone else will find use for this function too. As you may know, Microsoft botched implementing the Element.setAttribute method in IE up to version 7 (maybe 8). It won't work for setting the name attribute, so here's a workaround that will create the form field for you.

The only reason I'm posting it is that I'd like to think I didn't just spend 4 hours developing this just FOR MICROSOFT.


function createNewFormElement(tagname,type,name,value,form_name)
{
/*Use browser sniffing to determine if the browser is MSIE.
This method isn't perfect, but there's no easy way to test the
effectiveness of the setAttribute('name',) method.
*/
var isIE = false;
if(typeof(window.ActiveXObject) != 'undefined'){ isIE = true; }
else if(navigator.userAgent.indexOf('MSIE')!=-1){ isIE = true; }

//Create element and set name attribute (MSIE is very picky about this).
var newElement;
if(isIE){ newElement = document.createElement('<'+tagname+' name="'+name+'"/>'); }
else
{
newElement = document.createElement(tagname);
newElement.setAttribute('name',name);
}

//Set other attributes.
newElement.setAttribute('type',type);
newElement.setAttribute('value',value);

//Add to the document object.
document.forms[form_name].appendChild(newElement);
}

829 Designer
08-04-2008, 01:05 AM
Can you provide an example of this code in use?

Arty Effem
08-24-2008, 05:19 PM
Ok, I hope I'm not reinventing the wheel here so to speak. Hopefully someone else will find use for this function too. As you may know, Microsoft botched implementing the Element.setAttribute method in IE up to version 7 (maybe 8). It won't work for setting the name attribute, so here's a workaround that will create the form field for you.
This is normally done using a try-catch statement; you try it the Microsoft way then execute the compliant code in the catch block. No detection is necessary.