How to prevent onclick statements from being executed?

Posted by ryanli on Stack Overflow See other posts from Stack Overflow or by ryanli
Published on 2010-05-05T08:11:09Z Indexed on 2010/05/05 8:18 UTC
Read the original article Hit count: 155

Filed under:

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:

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="application/x-javascript">
        function addListener() {
            document.getElementById("submit").addEventListener("click",
                function(ev) {
                    alert("listener");
                    ev.preventDefault();
                },
                false);
        }
    </script>

    <title></title>

</head>

<body onload="addListener();">
<form id="form" method="post" target="">
<input type="submit" id="submit" onclick="alert('onclick')" value="test" />
</form>

</body>

</html>

The expected behaviour is only "listener" will be alerted, but in practice (Firefox 3.7a5pre), "onclick" and "listener" are both alerted, in the given order.

It seems that onclick is being executed before the listener, so event.preventDefault() doesn't work. Is there a way to prevent onclick from being executed?

© Stack Overflow or respective owner

Related posts about JavaScript