Mr. Mike
Mr. Mike

Reputation: 453

How to clear onClick before add new onClick event?

I try to replace an onclick event with other onclick event with javascript:

<button id='myButton' onClick=""/>

OLD onClick event :

$('#myButton').click(function(){
    alert('1');
});

and then i do the same like that and change the value of alert , i do like this :

$('#myButton').click(function(){
    alert('2');
});

The result of method above is alert show twice for 1 and 2. What i want is only 2 that must show (i replace alert('1') with alert('2'); not add another alert. How to fix my code?

Upvotes: 0

Views: 1835

Answers (3)

Mr. Mike
Mr. Mike

Reputation: 453

Finally the problem has been solved. I use method unbind like explain from here :

http://api.jquery.com/unbind/

For my case :

$('#myButton').unbind("click");

Thank you.

Upvotes: 0

bearwithbeard
bearwithbeard

Reputation: 331

You have 2 jQuery event listeners which listen same element. They know about element's id and this is enough for they work.

What I'm trying to say, that they don't care about onClick

You should code two JS functions, but not jQuery event listeners.

<button id='id' onClick="choose function"/>

function myFunction1() {
   //your code
}

function myFunction2() {
   //same
}

Upvotes: 0

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

Try this one:

$(document).off('click', '#myButton').on('click', '#myButton', function(){
    alert('2');
});

It will unbind previous event listener and add the new one.

Upvotes: 2

Related Questions