There is a <label>
with a <a href="#">
element inside. I'd like to prevent the default behaviour of the <a>
element (i.e. navigating) but it should execute the default behaviour of the <label>
element (i.e. checking the checkbox inside it).
Test case: http://jsfiddle.net/3M6WE/. Clicking foo
toggles the checkbox. Clicking bar
does not navigate but neither toggles the checkbox.
How can I have the <a>
element not navigate but have it toggle the checkbox? I'd like to avoid hacks like toggling the checkbox manually. I'm looking for a "partly" preventDefault
, if available.
The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault() . Nowadays, you should usually use native HTML form validation instead.
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.
Use preventDefault(); if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault() .
We can use the event. defaultPrevented property in the event object. It returns a boolean indicating if the event. preventDefault() was called in a particular element.
you could trigger the click of the parent element (the label):
http://jsfiddle.net/3M6WE/11/
$("a").on("click", function(e) {
e.stopPropagation();
$(this).parent().click();
// do stuff...
e.preventDefault();
});
then do some magic and finally call preventDefault();
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