JT Bradley JT Bradley - 27 days ago 6
Ajax Question

AJAX post data from cloned forms in one submit

I am posting multiple forms in one submit for a 'Refer a Friend' page. There is initially just 2 forms, one for the referrer and one for a referral. Users can 'add' more referral forms by clicking a plus sign which clone()s the referral form and append it to the container.

<div class="form-wrap">
<form id="referrer-form" role="form" action="<?=$_SERVER['REQUEST_URI'];?>" method="post" >
inputs...
</form>
<form id="first-ref" class="referral-form" role="form" action="<?=$_SERVER['REQUEST_URI'];?>" method="post">
inputs...
</form>
</div>
<div class="buttons">
<a id="plus" class="btn btn-primary" href=""></a>
<a id="minus" class="btn btn-danger" href=""></a>
<button id="submit" class="btn btn-warning btn-lg form-control">SUBMIT</button>
</div>


With my current jQuery, the 2 forms that are loaded with the page markup post just fine. However, the ones that have been clone()d are not posting. All the attributes appear the same.


// AJAX post on each form

var form = $('form');

$("#submit").click(function () {
$('#referrer', '#referrer-form').val('what is posted to leadsource field');
$(form).each(function () {
if ($(this).attr("id") != "referrer-form") {
$('#referrer', this).val('Referred by: ' + $('#referrer-form #name').val());
}
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
});
});
alert("form submitted");
$('form input').val('');
});

$("#plus").click(function () {
$("#first-ref").clone().appendTo(".form-wrap");
$(".referral-form").last().attr('id', '');
$(".referral-form").last().find('input').val('');
load_phoneMask_js();
});

$("#minus").click(function () {
$(".referral-form").last().remove();
});

</script>

Answer

jQuery's clone() has an argument in the form of .clone( [withDataAndEvents ] ), meaning if you want to keep data and events, you pass true

$("#first-ref").clone(true).appendTo(".form-wrap");

And make sure you get those forms inside the event handler

$("#submit").click(function () {
    var form = $('form');

    ... etc
Comments