Monday, October 27, 2008

Create dynamic form with javascript

hi,
ths function create a dynamic form with javascript
and submits it
it is useful when:
- u have to make several form submits in your page
- u want to avoid the server round trip

THE FUNCTION CODE:

function createFormAndSubmit(containerId,formName, formAttributes,inputsAttributes, submitName, clickSubmitBtn)
{
/*********************** Insructions *****************************
containerId -> use "" if u dont use container
formAttributes -> attName1=attValue1$attName2=attValue2
inputsAttributes -> input1Name=input1Value$input2Name=input2Value
******************************************************************/
// set the form attributes
var frm = document.createElement('form');
frm.setAttribute("name",formName);
var arrFormAttributes = formAttributes.split("$");
var nameVal, i, valFormAtt;
for(i=0; i< arrFormAttributes.length; i++)
{
nameVal = arrFormAttributes[i].split("=");
valFormAtt = arrFormAttributes[i].substring(nameVal[0].length+1,arrFormAttributes[i].length)
frm.setAttribute(nameVal[0], valFormAtt/*nameVal[1]*/);
}

// set the inputs attributes
var arrInputsAttributes = inputsAttributes.split("$");
var inputHidden;
for(i=0; i< arrInputsAttributes.length; i++)
{
nameVal = arrInputsAttributes[i].split("=");
inputHidden = document.createElement("input");
inputHidden.setAttribute("name",nameVal[0]);
inputHidden.setAttribute("type", "hidden");
var val1 = arrInputsAttributes[i].substring(nameVal[0].length+1,arrInputsAttributes[i].length);
inputHidden.setAttribute("value", val1);
frm.appendChild(inputHidden);
}
// set the submit button
var submitBtn = document.createElement("input");
submitBtn.setAttribute("name", submitName);
submitBtn.setAttribute("type", "submit");
submitBtn.setAttribute("value", "");
frm.appendChild(submitBtn);

// add the form to the document
var contId = document.getElementById(containerId);
if(contId == null)
{
document.body.appendChild(frm);
}
else
{
contId.appendChild(frm);
}
// submit the form
if(clickSubmitBtn == true)
{
submitBtn.click();
}
else
frm.submit();
// remove the form
if (frm.parentNode)
{
frm.parentNode.removeChild(frm);
}
}