简体   繁体   中英

preventDefault() not working for change event

Any ideas why preventDefault is not working? Here's the code below . . . Tks!

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

    $(document).ready(function() {
        $("#text1").change(function(e) {
             e.preventDefault();
        });
    });

function myFunc() {
    alert("Random, annoying alert");
}

</script>
</head>

Just one HTML element in the form:

<body>
<form name="test" method="post">
    <input name="text1" id="text1" type="text" onchange="myFunc();">
</form>
</body>

You can't use preventDefault on change events because it's not cancelable:

$("#text1").change(function(e) {
    alert(e.cancelable?"Is cancelable":"Not cancelable");
});

The cancelable property is true only on events that can be prevented.

preventDefault() is to be used to prevent the default behaviour of an element, that default behaviour is baked in to your browser.

Like for instance the behaviour of an anchor tag when clicked is to initiate a sequence of events that will modify the url bar and send a http request (Overly simplistic explanation I know).

By using evt.preventDefault(evt) inside a click event you can stop the default behaviour so that you can do other operations before you action the behaviour, or ignore it all together.

The issue i can see with your example is that the default behaviour of onchange is to deselect the input box, unhighlighting it and I am not sure that is classed as an event (I am pretty sure it isn't). Not for it to be able to stop a function you have attached onchange() . Infact if you were to use a preventDefault() , myFunc() is exactly where it should be.

For an event to be prevented there must be a resultant output, something beyond modifying appearance. eg The click of an a tag, the submit of a form, scroll of a container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM