NovoGeek's Blog (Archive)

Technical insights of a web geek

Beware – jQuery unbind() vs removeAttr()

Here is a jQuery bug which suck few hours of my time:

  1. unbind() works only on events attached using jQuery.
  2. removeAttr() does not work on events added using jQuery

Confusing? Here is the scenario which explains better:

I have a server side asp button(btnTest), for which an “onclick” event is attached on page load (in code behind) like this:

btnTest.Attributes.Add("onclick", "fnTestMethod()")

Without changing server side code, I need to change the functionality of button click (reason: deployment issues). So my initial approach was simple -  To unbind the click event from my asp button using jQuery like this:

$('#btnTest').unbind("onclick"); 
But this didn’t work!

I was confused! I didn’t understand how page life cycle was impacting DOM. After wasting a couple of hours, I remembered the removeAttr() and tried it:

$('#btnTest').removeAttr("onclick"); 

and it worked!
On googling, I came to know that this is a bug in jQuery’s tracker and it doesn’t have a fix. You may find a detailed explanation of the bug here.

In short, the explanation says that:
* unbind() works only on events attached using jQuery’s functions like bind(), click() etc. It didn’t work for me as I was binding in my server side code like: btnTest.attributes.add().
* removeAttr() does not work on events added using jQuery.

Hence, if you want to change the click event but not sure if you have added it from code behind or jQuery, write a safer code like this as suggested in the bug tracker:

$("#btnTest").removeAttr("onclick").unbind("click");

Mentioning about the bug here so that readers may not waste their time in similar scenarios. I still love jQuery a lotttt!!! :)

Comments (1) -

  • NovoGeek

    5/20/2009 1:15:15 AM |

    Hi Jonathan,
    bind() works absolutely fine and I am with you. But what I meant was unbinding events which are not attached by jQuery. Here is a working demo which shows the bug:
    http://labs.novogeek.net/blogcomments/unbind.aspx

    The first button still shows alert from server as well as client even though I unbound the server's event., where as the second button shows only alert from client event.
    Hope I am clear Smile

Pingbacks and trackbacks (1)+

Comments are closed