Question

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.

Was it helpful?

Solution

To do this without any libraries:

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

OTHER TIPS

With jQuery

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

And then proceed to add your own.

Try this, this is working for me:

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

See this for more details.

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

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.

If you want to remove ALL event-handlers on the element and its child-nodes and retain only the HTML structure, we can work with jQuery's clone():

var original, clone;
//
original = $('#my-div');
clone = original.clone();
//
original.replaceWith(clone);

This will effectively leave no event-handlers on the element or its child-nodes.

Good luck...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top