How to remove all click event handlers using jQuery?

JavascriptJqueryClick

Javascript Problem Overview


I'm having a problem. Basically, when a user clicks an 'Edit' link on a page, the following Jquery code runs:

$("#saveBtn").click(function () {
    saveQuestion(id);
});

By doing this, the onClick event of the save button calls the saveQuestion() method and passes on the ID of the question for which the 'Edit' link was clicked.

But if in the same session the user clicks edit on 2 questions, then instead of overwriting the previous click event handler, it instead causes 2 event handlers to run, one which might call saveQuestion(1) and the other might call saveQuestion(2). By doing this 1 question overwrites the other.

Is there a way to remove all previous click events that have been assigned to a button?

Javascript Solutions


Solution 1 - Javascript

You would use off() to remove an event like so:

$("#saveBtn").off("click");

but this will remove all click events bound to this element. If the function with SaveQuestion is the only event bound then the above will do it. If not do the following:

$("#saveBtn").off("click").click(function() { saveQuestion(id); });

Solution 2 - Javascript

> Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

Solution 3 - Javascript

$('#saveBtn').off('click').click(function(){saveQuestion(id)});

Solution 4 - Javascript

If you used...

$(function(){
    function myFunc() {
        // ... do something ...
    };
    $('#saveBtn').click(myFunc);
});

... then it will be easier to unbind later.

Solution 5 - Javascript

$('#saveBtn').off('click').on('click',function(){
   saveQuestion(id)
});

Use jquery's off and on

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - JavascriptTStamperView Answer on Stackoverflow
Solution 2 - JavascriptRafaelView Answer on Stackoverflow
Solution 3 - JavascriptFo NkoView Answer on Stackoverflow
Solution 4 - JavascriptJarrett MeyerView Answer on Stackoverflow
Solution 5 - JavascriptRohith K PView Answer on Stackoverflow