简体   繁体   中英

Javascript form being triggered by JQuery after changing id

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() .

Changing the id of an element doesn't remove existing handlers from it. Unbind it first:

$('#search_form').unbind('submit');

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM