Javascript:如果用户选中一个复选框,那么所有嵌套的复选框也被选中,我怎么能做到这一点?
假设我有:Javascript:如果用户选中一个复选框,那么所有嵌套的复选框也被选中,我怎么能做到这一点?,javascript,jquery,Javascript,Jquery,假设我有: <input id="album" name="album" type="checkbox" value="1" /> <label for="album">Albums</label><br> <ul> <li> <input id="albums_155596787784467" name="albums[155596787784467]" type="checkbox"
<input id="album" name="album" type="checkbox" value="1" />
<label for="album">Albums</label><br>
<ul>
<li>
<input id="albums_155596787784467" name="albums[155596787784467]" type="checkbox" value="1" />
<label for="albums_155596787784467">Profile Pictures</label><br>
</li>
<li>
<input id="albums_100358313308315" name="albums[100358313308315]" type="checkbox" value="1" />
<label for="albums_100358313308315">Perfil</label><br>
</li>
</ul>
当用户选中第一个复选框时,我希望ul中的所有复选框也被选中
$("input[name='album']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","ul").attr('checked',true);
} else
{
$("input[type='checkbox']","ul").attr('checked',false);
}
});
此外,如果ul内的任何复选框设置为未选中,则第一个复选框也应设置为未选中
$("input[name='album']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","ul").attr('checked',true);
} else
{
$("input[type='checkbox']","ul").attr('checked',false);
}
});
我使用JQuery
编辑:
此外,如果选中了ulare中的所有复选框,则也应选中第一个复选框
$("input[name='album']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","ul").attr('checked',true);
} else
{
$("input[type='checkbox']","ul").attr('checked',false);
}
});
编辑
对于示例的第2部分:
$("input[type='checkbox']","ul").each(function()
{
$(this).change(function()
{
if( ! $(this).is(':checked') )
{
$("input[name='album']").attr('checked',false);
}
$("input[name='album']").attr('checked',( $("input[type='checkbox']","ul").length == $("input[type='checkbox']:checked","ul").length ));
});
});
最好给ul一个id,然后试试下面的代码
$(function(){
$("#album").change(function(){
$("#ulid input:checkbox").attr("checked", this.checked);
});
var childCheckBoxes = $("#ulid input:checkbox");
var totalcheckBoxesCount = childCheckBoxes.length;
childCheckBoxes.change(function(){
var checkedBoxesCount = childCheckBoxes.filter(":checked").length;
$("#album").attr("checked", totalcheckBoxesCount === checkedBoxesCount);
});
});
试试这个
$(document).ready(function(){
$("#album").click(function(){
if($('#album').is(':checked'))
$("input[type=checkbox]").attr('checked','checked');
else
$("input[type=checkbox]").removeAttr('checked')
});
});
如果选中了所有子复选框,则不会选中主复选框。@Dawood:谢谢!你的代码就像一个符咒:Rahul确实捕捉到了我没有捕捉到的东西,如果选中了ul中的所有复选框,那么第一个复选框也应该被选中,这是有道理的。我会编辑这个问题。比较短和简单的是$input[type='checkbox'],ul.attr'checked',$this.is':checked';。不需要if=@dawood:mm,这有点违反直觉。即使“checked”属性更改,复选框的“value”也不会更改。对吗?