136

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?

simhumileco
  • 31,877
  • 16
  • 137
  • 115
Ali
  • 261,656
  • 265
  • 575
  • 769

5 Answers5

229

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); });
David Sherret
  • 101,669
  • 28
  • 188
  • 178
TStamper
  • 30,098
  • 10
  • 66
  • 73
15

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

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
Rafael
  • 18,349
  • 5
  • 58
  • 67
10
$('#saveBtn').off('click').click(function(){saveQuestion(id)});
pb2q
  • 58,613
  • 19
  • 146
  • 147
Fo Nko
  • 620
  • 10
  • 22
2

If you used...

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

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

Jarrett Meyer
  • 19,333
  • 6
  • 58
  • 52
  • 1
    How do you figure? No matter how a element's event are bound, they can always be unbound the same way... $('#saveBtn').unbind('whatever event(s)'); Now, to RE-BIND... yes, your technique may be easier in certain circumstances. – KyleFarris May 05 '09 at 17:44
  • 1
    If you unbind all click events, then it's no different. But if you only wanted to unbind one specific action, I wouldn't want to rewrite that event in two places. And as you said, if I want to rebind it later, that's again easier to do, because I don't have to write the function a third time. – Jarrett Meyer May 06 '09 at 12:53
0
$('#saveBtn').off('click').on('click',function(){
   saveQuestion(id)
});

Use jquery's off and on

Rohith K P
  • 3,233
  • 22
  • 28