Garrettj944 Garrettj944 - 6 months ago 12
jQuery Question

How to block click() on link inside of the element

I wasn't sure how to title this issue, but let me explain. I have a box with content, links, and a checkbox inside of it. If you click anywhere in the box, it will mark the checkbox. It will also do this if you click a link. How do I disable the checking of the box if you click a link, instead of the box? (confusing I know, see code snippet below)



$("div").on("click", function() {
var $checkbox = $(this).find(":checkbox");
$checkbox.prop("checked", !$checkbox[0].checked);
});

div {
width: 300px;
padding: 20px;
margin: auto;
background: #999;
color: #FFF;
}
input {
display: block;
height: 50px;
width: 50px;
margin: auto;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet urna risus. Maecenas egestas pellentesque sapien blandit hendrerit. Morbi tellus felis, elementum ut ligula eu, convallis luctus ante. <a href="https://www.google.com" target="_blank">Nulla molestie mollis aliquam.</a> Maecenas
nisl nulla, fringilla et placerat vitae, tempus ut urna.</p>
<input type="checkbox" name="check[]" class="check">
</div>




Answer

I guess a good'ol stopPropagation in the link's click handler would do the trick.

$("div a").on("click", function(e) {
  e.stopPropagation();
});

This prevents your click from bubbling to the div.

Updated snippet:

$("div").on("click", function(event) {
  var $checkbox = $(this).find(":checkbox");
  $checkbox.prop("checked", !$checkbox[0].checked);
});
$("div a").on("click", function(e) {
  e.stopPropagation();
});
div {
  width: 300px;
  padding: 20px;
  margin: auto;
  background: #999;
  color: #FFF;
}
input {
  display: block;
  height: 50px;
  width: 50px;
  margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet urna risus. Maecenas egestas pellentesque sapien blandit hendrerit. Morbi tellus felis, elementum ut ligula eu, convallis luctus ante. <a href="https://www.google.com" target="_blank">Nulla molestie mollis aliquam.</a> Maecenas
    nisl nulla, fringilla et placerat vitae, tempus ut urna.</p>
  <input type="checkbox" name="check[]" class="check">
</div>