I have a Button which is registered with a onclick
event as shown
<Input type="Button" name="Register" Value="Register" onclick="CallMe();"/>
Is it possible to programatically remove or deregister the onclick event on this Button?
The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.
Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.
To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.
In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.
You could set the onclick attribute to null
.
var el = document.getElementById('inputId');
el.onclick = null;
or better just remove the attribute altogether with the removeAttribute()
docs method of the element.
var el = document.getElementById('inputId');
el.removeAttribute('onclick');
you will need to add an id to the element though for this..
example code at http://jsfiddle.net/gaby/PBjtZ/
document.getElementsByName("Register")[0].onclick = ""
or
document.getElementsByName("Register")[0].removeAttribute("onclick")
Make sure to place this in a JS tag at the end of your document. So the DOM is available when this script is running.
the first example gets all elements with the name "Register" in your dom and returns the first, then it finds and sets the onclick attribute to an empty string. (could be null to)
the second example does the same, but removes the attribute "onclick".
Be careful if you have more then one element with the name "Register" you should do it like Gaby aka G. Petrioli told you to.
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