How to clear / remove JavaScript event handler?

Given the following HTML snippet:

<form id="aspnetForm" onsubmit="alert('On Submit Run!'); return true;"> 

I need to remove / clear the handler for the onsubmit event and register my own using jQuery or any other flavor of using JavaScript.

+56
javascript html javascript-events dom-events
Apr 29 '09 at 19:38
source share
6 answers

For this without any libraries:

 document.getElementById("aspnetForm").onsubmit = null; 
+81
Apr 29 '09 at 19:51
source share

With jQuery

 $('#aspnetForm').unbind('submit'); 

And then add your own.

+24
Apr 29 '09 at 19:41
source share

Try it, it works for me:

 $('#aspnetForm').removeAttr('onsubmit').submit(function() { alert("My new submit function justexecuted!"); }); 

See more details.

+11
Jun 09 2018-10-06T00:
source share

For jQuery, if you bind event handlers using .live, you can use .die to untie all instances associated with .live.

+2
Mar 29 '11 at 12:40
source share

Now this is an ancient question, but, given that all major browsers have abandoned EventTarget.getEventListeners() , there is a way to remove ALL event handlers for the element and its children and preserve only the HTML structure. We simply clone the element and replace it:

 let e = document.querySelector('selector'); let clone = e.cloneNode(true); e.replaceWith(clone); 

This is the same hack as addEventListener() method with a method that tracks each handler function, but at least it can be used after the DOM is already connected to other script events.

This also works in much the same way as above, using jQuery clone() instead of cloneNode() :

 let original = $('#my-div'); let clone = original.clone(); original.replaceWith(clone); 

This template will not actually leave event handlers on the element or its child nodes, unless they are defined using the attribute like onclick="foo()" .

+2
Dec 12 '17 at 7:27
source share

For jQuery, off() removes from it all the event handlers added by jQuery.

 $('#aspnetForm').off(); 

Calling .off () without arguments removes all handlers attached to elements.

+2
Jun 08 '18 at 3:54
source share



All Articles