2

i have 1 php page containing 2 forms and 1 submit button.i want to submit both forms with this single button.My code works perfectly but there is 1 problem that in each form only 1 field submitted successfully. Below is my html and javascript code, plz tell me where i have error

2 html forms

<form name="form">
      <input type="text" name="a" value="a">
      <input type="text" name="b" value="b">
</form>
<form name="form">
      <input type="text" name="c" value="c">
      <input type="text" name="d" value="d">
</form>

<input type="submit" name="Submit" id="button" value="Submit" onClick="submitAllDocumentForms()">

Javascript code

<script language="javascript" type="text/javascript">
/* Collect all forms in document to one and post it */
function submitAllDocumentForms() {
var arrDocForms = document.getElementsByTagName('form');
var formCollector = document.createElement("form");
with(formCollector)
{
method = "post";
action = "test.php";
name = "formCollector";
id = "formCollector";
}
for(var ix=0;ix<arrDocForms.length;ix++) {
appendFormVals2Form(arrDocForms[ix], formCollector);
}
document.body.appendChild(formCollector);
formCollector.submit();

}
/* Function: add all elements from ``frmCollectFrom´´ and append them to ``frmCollector´´ before returning ``frmCollector´´*/
function appendFormVals2Form(frmCollectFrom, frmCollector) {
var frm = frmCollectFrom.elements;
for(var ix = 0 ; ix < frm.length ; ix++)
frmCollector.appendChild(frm[ix]);
return frmCollector;
}
</script>

My php code to echo submitted values

<?php
echo $_POST['a'];
echo $_POST['b'];
echo $_POST['c'];
echo $_POST['d'];
?>

1 Answer 1

2

The problem is that appendChild() takes the element away from the form, modifying the elements array as well as its length. To avoid this, you can e.g. store the number of elements in a variable and process the array of elements starting from the last element:

var frm = frmCollectFrom.elements; 
var nElems = frm.length;
for(var ix = nElems - 1; ix >= 0 ; ix--)
  frmCollector.appendChild(frm[ix]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.