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