JQuery:复选框如何在选择另一个复选框时选中或取消选中所有复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19569510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery: Checkbox how to check or uncheck all checkboxes when another checkbox is selected
提问by Atish
When i select/unselect selectAll checkbox I want all the other checkbox to be checked or unchecked.
当我选择/取消选择 selectAll 复选框时,我希望选中或取消选中所有其他复选框。
There is no child or parent element
没有子元素或父元素
Html Code:
html代码:
<div>
<li class="input">
<input type="checkbox" name="selectAll" value=""></input>
</li>
<li class="input">
<input type="checkbox" name="practice" value=""></input>
</li>
<li class="input">
<input type="checkbox" name="filename" value=""></input>
</li>
<li class="input">
<input type="checkbox" name="comment" value=""></input>
</li>
</div>
This is what i tried to do so far -
这是我到目前为止尝试做的 -
$(this).siblings('ul').find("input[type='checkbox']").prop('checked', true);
and
和
$(this).parent().find('input:checkbox:first').prop('checked', true);
回答by Saran
Here you go.
干得好。
Markup:
标记:
<div>
<li class="input">
<input type="checkbox" id="select-all" name="selectAll" value=""/>
</li>
<li class="input">
<input type="checkbox" name="practice" value=""/>
</li>
<li class="input">
<input type="checkbox" name="filename" value=""/>
</li>
<li class="input">
<input type="checkbox" name="comment" value=""/>
</li>
</div>
Code:
代码:
$("#select-all").on("click", function() {
var all = $(this);
$('input:checkbox').each(function() {
$(this).prop("checked", all.prop("checked"));
});
});
Fiddle: http://jsfiddle.net/PcMnk/148/
回答by kasdega
HTML
HTML
<div>
<li class="input">
<input type="checkbox" class="select-all" name="selectAll" value=""></input>
</li>
<li class="input">
<input type="checkbox" class="item-checkbox" name="practice" value=""></input>
</li>
<li class="input">
<input type="checkbox" class="item-checkbox" name="filename" value=""></input>
</li>
<li class="input">
<input type="checkbox" class="item-checkbox" name="comment" value=""></input>
</li>
</div>
Jquery
查询
$(".select-all").on("click", function() {
$(".item-checkbox").prop("checked", $(this).prop("checked"));
});
OR (if you can't assign a class for some reason)
或(如果您由于某种原因无法分配课程)
$("input[name=selectAll]").on("click", function() {
$("input:checkbox").prop("checked", $(this).prop("checked"));
});
OR (if you only want the checkboxes that are at a similar level in the DOM
或者(如果您只想要在 DOM 中处于相似级别的复选框
$("input[name=selectAll]").on("click", function() {
$(this).closest("div").find("input:checkbox").prop("checked", $(this).prop("checked"));
});