There is a button labeled NEWFORM to create a new form when clicked. Each form has a submit button. When the submit button of each form is clicked, the values of that form will be sent via AJAX. My code works well the first time, but when a new form is created and submitted, all of the values of all forms will send together.
Here is my snippet:
$(document).ready(function() {
$(".newform").click(function() {
$(".MyForm")
.eq(0)
.clone()
.show()
.insertAfter(".MyForm:last");
});
$(document).on('click', '.MyForm button[type=submit]', function(e) {
e.preventDefault() // To make sure the form is not submitted
$('.MyForm').each(function() {
console.log($(this).serialize())
$.ajax(
$(this).attr('action'),
{
method: $(this).attr('method'),
data: $(this).serialize()
}
)
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
<form class="MyForm" method="post">
<input type="text" placeholder="name" value="Aynaz" name="a1" />
<select name="Avg">
<option value="1">1</option>
<option value="2">2</option>
</select>
<button type="submit">Submit</button>
</form>
</div>
You iterate all ".MyForm" objects in your solution, so all of them submitted, you need to determine correct form in onClick first, and then submit it:
$(document).ready(function() {
$(".newform").click(function() {
$(".MyForm")
.eq(0)
.clone()
.show()
.insertAfter(".MyForm:last");
});
$(document).on('click', '.MyForm button[type=submit]', function(e) {
e.preventDefault() // To make sure the form is not submitted
var $frm = $(this).closest('.MyForm');
console.log($frm.serialize());
$.ajax(
$frm.attr('action'),
{
method: $frm.attr('method'),
data: $frm.serialize()
}
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
<form class="MyForm" method="post">
<input type="text" placeholder="name" value="Aynaz" name="a1" />
<select name="Avg">
<option value="1">1</option>
<option value="2">2</option>
</select>
<button type="submit">Submit</button>
</form>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With