I'm going nuts just trying to unbind an onclick handler from the event in jQuery so I can bind it later on to another function.
I have isolated the code in a test page so there's nothing but the meat, just a button that calls a function and a script that tries to unbind it:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript">
</script>
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() { $("#btnNext").unbind('click'); });
function hi() {window.alert("hi");}
</script>
</head>
<body>
<input id="btnNext" type="button" value="Next" onclick="hi();" />
</body>
</html>
Anybody knows why the click event keeps calling the hi() function no matter what I said in the document.ready?
Thanks
Use the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.
jQuery off() Method The off() method is most often used to remove event handlers attached with the on() method. As of jQuery version 1.7, the off() method is the new replacement for the unbind(), die() and undelegate() methods.
Because you put it in the html attribute, it stays there. It was not bound with jQuery so jQuery is not tracking it's usage.
$("a").bind('click',hi);
$("a").unbind('click',hi);
http://docs.jquery.com/Events/bind
Just for the record, you can use the removeAttr
jQuery function to remove the initially specified onclick
attribute.
$('#btnNext').removeAttr("onclick");
Also, in response to Chad, I agree that it is generally better to do all your binding with jQuery, but I'm in a situation (using ASP.NET MVC) that requires individual links to have some model parameters in their click event handlers. It would be more convoluted IMO to try to wire up these event handlers via jQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With