Skip to content Skip to sidebar Skip to footer

How To Prevent Onclick Statements From Being Executed?

I want to use an event listener for preventing the onclick statement of a submit button, however, using event.preventDefault() doesn't work as intended. The code is like this: <

Solution 1:

DOM0 handlers (onclick attributes and the like) and DOM2 handlers (dynamically added via attachEvent/addEventListener) are independent of one another.

The only thing you can do is remove the DOM0 handler (by assigning an empty string to the attribute) and go with just DOM2 handlers.

You can retrieve the DOM0 handler from the attribute before removing it, and re-register it as a DOM2 handler instead. You get into some browser inconsistencies (some will give you a Function object, others will give you a string), but those are readily handled in the code.

Solution 2:

You can try this:

functionaddListener() {
        document.getElementById("submit").addEventListener("click",
            function(ev) {
                alert("listener");
                ev=ev¦¦event; 
                ev.preventDefault? ev.preventDefault() : ev.returnValue = false; 
            },
            false);
    }

Post a Comment for "How To Prevent Onclick Statements From Being Executed?"