Preventing checkbox from being deselected when click trigger is on parent element
Kind of a funny problem here.
I want to check the checkbox when the parent div is checked, but it is DESELECTING the checkbox when the CHECKBOX is clicked on ;)
It works fine when the name is clicked on. How do i solve this?
//layout
<div class开发者_如何学编程="parent">
<input type="checkbox"/> <a>Name</a>
</div>
//check the box when parent div is clicked
$(".parent").click(function(event){
event.preventDefault();
checkbox=$(this).find("input:checkbox");
checkbox.attr("checked","checked");
});
Try this.
<div class="parent">
<input type="checkbox" class="check"/> <a>Name</a>
</div>
$(".parent").click(function(event){
$(".check:not(:checked)").attr('checked','checked');
});
$(".check").click(function(event){
event.stopPropagation();
});
jsFiddle is here
Try adding:
event.stopPropagation();
return false;
to your event handler.
So, your code looks like:
//layout
<div class="parent">
<input type="checkbox"/> <a>Name</a>
</div>
//check the box when parent div is clicked
$(".parent").click(function(event){
event.stopPropagation();
event.preventDefault();
checkbox=$(this).find("input:checkbox");
checkbox.attr("checked","checked");
return false;
});
...
Documentation for event.stopPropagation():
http://api.jquery.com/event.stopPropagation/
I haven't tried it, but I suspect you can prevent the parent's action from running by preventing the event from bubbling like so:
$(".parent input:checkbox").click(function(event) {
event.stopPropagation();
});
Alternatively, you could just put your click handler on the <a>Name</a>
element or use a <label>
element without adding any JS (this is exactly what <label>
is for).
精彩评论