Reputation: 1387
I have a form that, once submitted, executes some JQuery using $('#search_form').submit(function(){# execute code here});
. Later on in the code, I change the id of the form with $('#search_form').attr('id', 'tags_form');
. Then, I have a different block of code when that form is triggered. The problem is that when I submit the form with the new id, it still triggers the old .submit()
.
Upvotes: 0
Views: 59
Reputation: 123739
Yes of course because when you bound the event using new id tags_form
at the start up it doesn't just exist. So event binding is of no effect there.
instead try using event delegation or bind the event after changing the id, or assign a classname for element and bind the event to the classname instead of the id.
$(document).on('submit', '#tags_form, #search_form', function(){# execute code here});
Or:
$('.myFormClass').submit(processForm); //where the classname on form is myFormClass
Or:
Say you event is like this:
$('#search_form').on('click', processForm); // or $('#search_form').click(processForm);
Later:
// some code...
$('#search_form').off('submit'); // unbind the handler or $('#search_form').unbind('click');
//In the Code block that changes the id
$('#tags_form').on('submit', processForm); // bind the handler to new element
Upvotes: 1
Reputation: 25221
Changing the id
of an element doesn't remove existing handlers from it. Unbind it first:
$('#search_form').unbind('submit');
Upvotes: 3