I have a user input page which loads different forms with ajax depending on some options the user has. I want to save this forms data with AJAX as well, but it only works with the first form that is loaded. Once the user changes the options, and a different form is loaded, the change of the form behaviour applied with jQuery no longer works.
I guess this is happening because the script is applying the new behaviour to the form that is currently on the page, but not to forms that are loaded later, right?
I already tried encapsulating the $(‘form’).submit()… etc in a function and calling it everytime a new form is loaded, but it doesnt work either…
Then, how can i solve this? This is my code (some of it):
function showFormUpdate(month, show) {
//actualiza el formulario por ajax
$('#showFormWrapper').fadeOut();
$.post("../inc/ajax-select-show.php", {month: month, show: show}, function(data){
$('#showFormWrapper').html(data);
whatIsActive ();
});
$('#showFormWrapper').fadeIn();
}
function showFormsend () {
$.post("../inc/ajax-saveshowform.php",
{
activeShow: $('input#activeShow').val(),
activeMonth: $('input#activeMonth').val(),
everyday: $('input#everyday').val(),
mon: $('input#mon').val(),
tue: $('input#tue').val(),
wed: $('input#wed').val(),
thu: $('input#thu').val(),
fri: $('input#fri').val(),
sat: $('input#sat').val(),
sun: $('input#sun').val()
}, function(data){
alert (data);
});
}
$(document).ready(function() {
$('a.changeForm').click(function(event){
event.preventDefault();
if ($(event.target).hasClass('changeShow')){
showFormUpdate($('input[name="activeMonth"]').val(), $(event.target).attr('show'));
}
if ($(event.target).hasClass('changeMonth')){
showFormUpdate($(event.target).attr('month'), $('input[name="activeShow"]').val());
}
});
//this is the part that changes the functionality of the form,
//but only works with the first loaded form
$('.showForm').submit(function(event){
showFormsend ();
return false;
})
});
You might have to use the live function with your events. When you destroy/re-add items that matched a raw event function when jQuery loaded (like .click or .submit) their events are gone once they are removed.
To get around this use .live which will apply the event to all existing and future-added elements that match your selector: