Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a link inside a label from triggering a checkbox?

I have this label:

<label><input type="checkbox"> I agree to the <a href="terms">terms</a> and would like to continue</label> 

However, the link inside the label opens a foundation 5 reveal modal. This works fine, but clicking on the link also checks the checkbox.

How can I prevent the checkbox from being checked when the link is clicked?

like image 974
kevinius Avatar asked Jul 15 '14 10:07

kevinius


People also ask

How to prevent checkbox check when clicking on link inside label?

You can cancel the click event by routing it through an onclick event. The "return false;" part will prevent the click event from moving up to the label.

Should checkbox label be clickable?

Clickable Checkbox LabelWithout label tags, users can't click the label to tick the checkbox. Instead, they have to click the checkbox itself. This causes users to struggle because the checkbox is a small target to hit especially for motor-impaired users.


1 Answers

You should just need to bind an event to the link that calls event.stopPropagation() and event.preventDefault()

JQuery for all links in labels:

$(document).on("tap click", 'label a', function( event, data ){     event.stopPropagation();     event.preventDefault();     window.open($(this).attr('href'), $(this).attr('target'));     return false; }); 

Pure javascript (you need to set an id on the link you want to follow)

var termLink = document.getElementById('termLink'); var termClickHandler = function(event) {     event.stopPropagation();         event.preventDefault();     window.open(termLink.href, termLink.target);     return false; }; termLink.addEventListener('click', termClickHandler); termLink.addEventListener('touchstart', termClickHandler); 

These expect the link target to be set to _self or _blank to open in the same window or a new window respectively.

like image 200
elvey Avatar answered Sep 22 '22 08:09

elvey