Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 952
SlimJim Avatar asked Jun 16 '14 20:06

SlimJim


People also ask

How do I stop Onchange events?

Solution 1. The idea is simple: don't prevent events. Don't make your code overly complex and error-prone by registering and unregistering any events. Add all event handlers only once and never change them.

In which situation we can use preventDefault?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What does event preventDefault () do?

preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.


2 Answers

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.

like image 126
Fiambre Avatar answered Sep 29 '22 00:09

Fiambre


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. e.g. The click of an a tag, the submit of a form, scroll of a container.

like image 43
Chris Rymer Avatar answered Sep 29 '22 00:09

Chris Rymer