我有一个动态表单,其中有许多复选框。我想创建一个“全选”方法,单击该方法时会自动检查表单中的所有框。
[x] select all //<input type="checkbox" id="select-all"> Select all
[] item 1 //<input type="checkbox" id="1" class="checkbox1" value="1">
[] item 2 //<input type="checkbox" id="2" class="checkbox1" value="2">
[submit]
我的 jQuery 如下:
$(document).ready(function(){
$('#select-all').click(function() {
if (this.checked)
{
console.log("Check detected");
$('.checkbox1').each(function() {
console.log('Checking the item with value:' + this.value );
$(this).prop('checked', true);
console.log(this);
});
} else {
console.log("not checked");
}
});
});
我的控制台输出:
> Check detected
> Checking the item with value:1
> <input type="checkbox" id="1" class="checkbox1" value="1">
> Checking the item with value:2
> <input type="checkbox" id="2" class="checkbox1" value="2">
我可以循环遍历每个项目,但是,我不确定如何实际将复选框设置为选中。
我正在努力解决的部分是检查状态的实际设置,我知道我需要使用: .prop('checked',true) 但是,我对实际元素使用什么? $(this) 显然不起作用...
$(this).prop('checked', true);
最佳答案
使用这个简单的代码
$(".checkAll").change(function(){
$('.checkbox1').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Check all</label>
<input type="checkbox" class="checkAll" />
<br/><br/>
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
<input type="checkbox" class="checkbox1" />
关于javascript - 使用 Jquery 设置复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38028792/