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

Another inline way:

<label>
     <input type="checkbox"> 
     I agree to the 
     <span  onclick="event.stopPropagation();">
          <a href="terms">terms</a>
     </span>
     and would like to continue
</label>

Since multiple labels can point to the same checkbox, you can modify the text to consist of two labels (pointing to the checkbox) and the anchor text in the middle.

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

Using the above technique, clicking on the link doesn't effect the state of the checkbox, yet all the remaining text does.


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.


Interactive elements inside interactive elements cause functional problems like this: it is undefined what happens when you click an a element inside a label element or vice versa. To avoid this, take the a element out of the label element, e.g.

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

or

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