Reputation: 189
I searched and found the nice code from here. Submit a form using jQuery
<input type='button' value='Submit form' onClick='submitDetailsForm()' />
<script language ="javascript" type = "text/javascript" >
function submitDetailsForm()
{
$("#formId").submit();
}
</script>
But can you please advise how to deal with multiple form within a page such?
<form id="myForm1" action="comment.php" method="post"></form>
<form id="myForm2" action="comment.php" method="post"></form>
<form id="myForm3" action="comment.php" method="post"></form>
<form id="myForm4" action="comment.php" method="post"></form>
Upvotes: 3
Views: 17626
Reputation: 3348
/* get all form and loop foreach */
$( "form" ).each( function() {
/* addEventListener onsubmit each form */
$( this ).bind( "submit", function(event) {
/* return false */
event.preventDefault();
/* display each props of forms */
console.log( event.target ); // object formHTML
console.log( "form id: " + event.target.id );
console.log( "form action: " + event.target.action );
console.log( "form method: " + event.target.method );
} );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm1" action="comment1.php" method="post">
<input type="submit" value="Submit Form1" />
</form>
<form id="myForm2" action="comment2.php" method="post">
<input type="submit" value="Submit Form2" />
</form>
<form id="myForm3" action="comment3.php" method="post">
<input type="submit" value="Submit Form3" />
</form>
<form id="myForm4" action="comment4.php" method="post">
<input type="submit" value="Submit Form4" />
</form>
Upvotes: 1
Reputation: 11431
I would suggest putting a class on every input button you wish to submit like this.
For example you could have some forms like this:
<form id="form1">
<!--Form elements-->
<input class="submitButton" type="button" value="submit" />
</form>
<form id="form2">
<!--Form elements-->
<input class="submitButton" type="button" value="submit" />
</form>
You could then use jQuery to submit them like this:
$(".submitButton").click(function() {
//Select the parent form and submit
$(this).parent("form").submit();
});
Upvotes: 9
Reputation: 621
There is no way to accomplish this without Ajax. When you submit a form you are in fact making an http request, so a whole new html page will load.
The only way to avoid this is by sending the form via Ajax, so you can control the response of the petition (and therefore nothing stops you from sending more than one form via this way).
You can achieve this with this jQuery plugin
Upvotes: 1