Jordan Terrell
Jordan Terrell

Reputation:

How to Clear/Remove JavaScript Event Handler?

Given the following HTML fragment:

<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 JavaScript usage.

Upvotes: 64

Views: 110040

Answers (6)

Aakash
Aakash

Reputation: 23717

This is an ancient question now, but given that the major browsers have all abandoned EventTarget.getEventListeners(), here's a way to remove ALL event handlers on the element and its children and retain 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 just as much of a hack as preempting the addEventListener() prototype with a method that keeps track of every handler function, but at least this can be used after the DOM is already wired up with another script's events.

This also works about the same as above using jQuery's clone() instead of cloneNode():

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

This pattern will effectively leave no event handlers on the element or its child nodes unless they were defined with an "on" attribute like onclick="foo()".

Upvotes: 6

zwcloud
zwcloud

Reputation: 4889

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

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

Calling .off() with no arguments removes all handlers attached to the elements.

Upvotes: 3

Brian DiCasa
Brian DiCasa

Reputation: 9487

For jQuery, if you are binding event handlers with .live, you can use .die to unbind all instances that were bound with .live.

Upvotes: 2

jiggy
jiggy

Reputation: 3826

To do this without any libraries:

document.getElementById("aspnetForm").onsubmit = null;

Upvotes: 87

Ryan
Ryan

Reputation: 111

Try this, this is working for me:

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

See this for more details.

Upvotes: 11

Peter Bailey
Peter Bailey

Reputation: 105868

With jQuery

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

And then proceed to add your own.

Upvotes: 26

Related Questions