Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to partly preventDefault()?

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.

like image 975
pimvdb Avatar asked Jul 06 '12 14:07

pimvdb


People also ask

What can I use instead of event preventDefault?

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.

What is e preventDefault () method?

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.

How do you set preventDefault to false?

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() .

How can you check if the event preventDefault () method was used in an element?

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.


1 Answers

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();

like image 127
Reinder Wit Avatar answered Oct 07 '22 14:10

Reinder Wit