jQuery Selector: If one checkbox is checked then I also want to change the attribute of the other checkbox in the same row to checked
I have a large table. In each row is two checkboxes. If one is checked then I also want to change the attribute of the other checkbox in the same row to checked.
My Code on Paste Bin
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".BookTable input[name=attended]").click(function() {
if ($(this).attr("checked") == true)
{
$("input").parent().parent("input[name=attended]").attr("checked","yes");
}
});
});
</script>
<table class="BookTable adj-table">
<tr>
<td>Joe</td>
<td>Bloggs</td>
<td><input name="booking" id="booking" type="checkbox" value="1" /></td>
<td><input name="attended" id="attended" type="checkbox" value="1" /></td>
</tr>
<tr>
<td>Dave</td>
<td>Smith</td>
<td><input name="booking" id="booking" type="checkbox" value="1" /></td>
<td><input name="attended" id="attended" type="checkbox" value="1" /></td>
</tr>
</table&开发者_如何学编程gt;
So far I can only seem to get it selecting all checkboxes.
You can use .closest()
to go up to the <tr>
then .find()
inputs inside, like this:
$(".BookTable :checkbox").change(function() {
$(this).closest("tr").find(":checkbox").attr("checked", this.checked);
});
You can test it out here. If you only want to check but not un-check the other, just add an if()
in there like this:
$(".BookTable :checkbox").change(function() {
if(this.checked)
$(this).closest("tr").find(":checkbox").attr("checked", true);
});
$(".BookTable :checkbox").click(function(){
if ($(this).is(":checked"))
$(this).parents("tr").find(":checkbox").attr("checked", "checked");
else
$(this).parents("tr").find(":checkbox").removeAttr("checked");
});
You can't have two id's with the same name you should make them a class
精彩评论