是否可以使用jQuery仅检查刀片模板内表中属于行的复选框?我有这个表格视图
我只希望检查属于7-A的学生,而不包括7-B的学生。我该如何运作?
我正在使用for-each
循环在表中显示数据。使用我当前的jQuery代码,它将检查表中的所有项目。
查看表:
<table class="table table-hover table-bordered" >
<tr>
<th>Section</th>
<th>Student</th>
</tr>
@foreach($sections as $section)
<tr>
<td>
<input type="checkbox" id="chckHead" />
<label>{{$section->section_code}}<label>
</td>
<td>
@foreach($section->lead as $bt)
<input type="checkbox" class="chcktbl" name="lead_id[]" value="{{$bt->id}}">
<label>{{$bt->student_name}}</label>
@endforeach
</td>
</tr>
@endforeach
</table>
脚本
$('#chckHead').click(function() {
if (this.checked == false) {
$('.chcktbl:checked').attr('checked', false);
} else {
$('.chcktbl:not(:checked)').attr('checked', true);
}
});
$('#chckHead').click(function () {
});
答案 0 :(得分:1)
使用$(this).parents('tr')
获取当前表行,并使用find选中当前行中的复选框。
$('#chckHead').click(function () {
if (this.checked == false) {
$(this).parents('tr').find('.chcktbl:checked').attr('checked', false);
}
else {
$(this).parents('tr').find('.chcktbl:not(:checked)').attr('checked', true);
}
});
或者只是做:
$('#chckHead').click(function () {
$(this).parents('tr').find('.chcktbl:checked').attr('checked', this.checked);
});
示例:
$(document).ready(function(){
$('.selectAll').on('click', function(){
$(this).parents('tr').find('.student').prop('checked', this.checked)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td style="border: 1px solid;vertical-align: top">
<label>All A<input type="checkbox" class="selectAll"></label></td>
<td style="border: 1px solid">
<label>Student A1<input type="checkbox" class="student"></label><br>
<label>Student A2<input type="checkbox" class="student"></label><br>
<label>Student A3<input type="checkbox" class="student"></label>
</td>
</tr>
<tr>
<td style="border: 1px solid;vertical-align: top">
<label>All B<input type="checkbox" class="selectAll"></label></td>
<td style="border: 1px solid">
<label>Student B1<input type="checkbox" class="student"></label><br>
<label>Student B2<input type="checkbox" class="student"></label><br>
<label>Student B3<input type="checkbox" class="student"></label>
</td>
</tr>
<tr>
<td style="border: 1px solid;vertical-align: top">
<label>All C<input type="checkbox" class="selectAll"></label></td>
<td style="border: 1px solid">
<label>Student C1<input type="checkbox" class="student"></label><br>
<label>Student C2<input type="checkbox" class="student"></label><br>
<label>Student C3<input type="checkbox" class="student"></label>
</td>
</tr>
</table>