Reputation: 1167
I have a DOM structure sometihng like this (I don't want to show other td's because of overcrowding):
<table>
<tr><td><input type="checkbox" name="checkbox1" class="rowSelectCheckbox"></td></input></tr>
<tr><td><input type="checkbox" name="checkbox2" class="rowSelectCheckbox"></td></input></tr>
<tr><td><input type="checkbox" name="checkbox3" class="rowSelectCheckbox"></td></input></tr>
<tr><td><input type="checkbox" name="checkbox4" class="rowSelectCheckbox"></td></input></tr>
</table>
<input type="checkbox" name="checkbox_select" id="lastCheckbox"></input>
What I'm trying to do is set the last checkbox with the id of lastCheckbox to checked if any of the other checkboxes are checked (any of those with id of checkbox1, checkbox 2 etc), otherwise if all the other checkboxes are unchecked, set this last checkbox to unchecked too.
Upvotes: 0
Views: 266
Reputation: 31580
A quick if-test should do this:
$("input.rowSelectCheckbox").change(function(){
if ( $("input.rowSelectCheckbox:checked") ) { //include "rowSelectCheckbox" so id=lastCheckbox doesn't trip the test
$("input#lastCheckbox").attr("checked");
}
else
$("input#lastCheckbox").removeAttr("checked");
}
});
A loop, such as .each(), is unnecessary since you only care if (any) one of input.rowSelectCheckbox
is checked. This will return true the first time it encounters an <input class="rowSelectCheckbox" />
that is checked ;)
Upvotes: 0
Reputation: 15765
You should do something like this:
$('.rowSelectCheckbox').change( function() {
flag = false;
$('.rowSelectCheckbox').each( function() {
if ($(this).is(':checked')) {
flag = true;
}
});
$('#lastCheckbox').prop('checked', flag);
});
Live demonstration here: http://jsfiddle.net/nayish/teXHe/
Upvotes: 0
Reputation: 3770
One little niggle: the closing </input>
tag belongs before the </td>
tag.
Otherwise it's pretty straightforward.
$(".rowSelectCheckbox").click(function(){
var lastCheckbox = $("#lastCheckbox");
if $(".rowSelectCheckbox:checked").length) {
lastCheckbox.attr("checked", "checked");
} else {
lastCheckbox.removeAttr("checked");
}
});
Upvotes: 1
Reputation: 101483
The following jQuery should do the trick
$(document).ready(function() {
$(".rowSelectCheckbox").click(function() {
var numChecked = $(".rowSelectCheckbox").filter(":checked").length;
if(numChecked > 0)
{
$("#lastCheckbox").prop("checked", "checked");
}
else
{
$("#lastCheckbox").prop("checked", false);
}
});
});
This will count the number of checked checkboxes when any one of them is clicked and, if this number is greater than 0, check the last checkbox outside the table.
There's a working example here.
Upvotes: 0
Reputation: 4495
Try this:
$('.rowSelectCheckbox').change( function() {
$('.rowSelectCheckbox').each( function() {
if ($(this).prop('checked')) {
$('#lastCheckbox').prop('checked', true);
return false;
}
$('#lastCheckbox').prop('checked', false);
} );
} );
Fiddle: http://jsfiddle.net/B78vP/
Upvotes: 0