Reputation: 17752
I'm wondering if there is a way in jQuery to check/uncheck a checkbox when someone clicks an entire div layer. Like having a massive selection area, essentially.
Any ideas?
Here is an example... I am trying to make the around the checkbox clickable to toggle the individual checkbox, pretty much.
<fieldset>
<div>
<input type="checkbox" id="Checkbox1" />
</div>
Person 1<br />
</fieldset>
<fieldset>
<div >
<input type="checkbox" id="Checkbox2" />
</div>
Person 2<br />
</fieldset>
Upvotes: 4
Views: 18232
Reputation: 41
When you want to make this work both to click on the div and input inside it, and also trigger change function, you can use following code:
$('input').change(function() {
console.log('change triggered')
}).click(function(event) {
event.stopPropagation()
})
$('div').click(function() {
var c = $this.find('input')
c.attr('checked', (!c.is(':checked')).change()
})
Upvotes: 4
Reputation: 6887
$('fieldset div').bind('click', function() {
var checkbox = $(this).find(':checkbox');
checkbox.attr('checked', !checkbox.attr('checked'));
});
Upvotes: 6
Reputation: 3060
Perhaps use the clicked div as the parent.
$(function() {
$('#divId').toggle(
function(event) {
$(this).find('input').attr('checked', true);
},
function(event) {
$(this).find('input').attr('checked', false);
}
);
});
This should only check the boxes inside the #divId that's clicked.
Upvotes: 6
Reputation: 1061
$(function() {
$('#divId').toggle(
function(event) {
$('input[name=foo]').attr('checked', true);
},
function(event) {
$('input[name=foo]').attr('checked', false);
}
);
});
Upvotes: 0
Reputation: 10174
Your check all checkbox:
<input type="checkbox" id="checkAll" /> Check All
And your JS code:
$('#checkAll').click(function() {
if($(this).attr('checked')) {
$('input:checkbox').attr('checked', false);
} else {
$('input:checkbox').attr('checked', true);
}
});
Upvotes: 0