I have several forms(user can add new form dynamically) in one page, they’re all submitted to the same struts2 action. I need to submit all these forms when the user clicks the save button.
Things go well in FF. But in IE and Google chrome, only the last form is submitted.
Any help is appreciated. Thank you.
Each form’s elements are the same, one form one object. Every form’s data will be added to an domain object then the object will be persisted to DB.
JavaScript function to handle save operation:
<script type="text/javascript" >
function submit() {
var formCnt = document.getElementById('formCnt').value;
for(var i = 1; i <= formCnt; i++) {
var formName = 'form' + i;
document.forms[formName].submit();
}
}
</script>
...
<input type="hidden" id="formCnt" name="formCnt" value="5" />
<form action="add.htm" name="form1" id="form1" method="post" enctype="multipart/form-data" />
<input type="text" name="item.price" id="item.price" value="" />
...
</form>
<form action="add.htm" name="form2" id="form2" method="post" enctype="multipart/form-data" />
<input type="text" name="item.price" id="item.price" value="" />
...
</form>
...
<form action="add.htm" name="form5" id="form5" method="post" enctype="multipart/form-data" />
<input type="text" name="item.price" id="item.price" value="" />
...
</form>
...
You should only be able to submit one form at a time. A submit button must be inside
<form>tags, and only the form that the submit button is in should be submitted. That hiddeninputtag there should be inside a form tag as well BTW.Even when doing it via JS, a
submit()initiates a newPOSTrequest to the server. You can only make one request at a time, that’s why only the last shows up. I have no idea why it would work in FF.If you need to submit everything at once anyway, why break it up to begin with? If you want “subsections” in a form, you can use the
<fieldset>tags.Edit
What happens when you run your script is the same as if all your forms have a submit button, and you click all submits buttons in rapid order. Clicking one submit button sends the data of that form to the server in a
POSTrequest and refreshes the page. If you’re fast enough to click another button before the page refreshes, you can submit another form, the old request will be canceled.The only way I can imagine how the data of all forms could possibly get to the server the way you’re doing it is if the request happens to be send before the next
submit()is triggered. Essentially you’re relying on the browser being slow, or at least handling the request before continuing the script execution. Apparently that works in FF, but fails in other browsers. As it should.Edit 2
If you need to submit multiple fields with the same name, use one form and give your fields unique names. The best naming scheme depends on how your backend handles form submissions.
item0,item1item.0,item.1Model.0.item,Model.1.item