Parent element
Child element
Child element
Parent element2
Child element2
Child element2
Parent element3
Parent element4
页面上有一些复选框。我需要: 如果选中父母,则检查所有孩子。 如果未选中所有子项,则取消选中父项。 检查父母是否至少检查了一个孩子。
这是一些代码,但是不起作用
$('input[type=checkbox]').change(function() {
var id = $(this).attr('id');
var children = $('.parent-' + id);
//Is this a child
if (children.length)
{
//Is it checked
if ($(this).is(':checked'))
{
//Find the parent
var className = $(this).attr('class');
var pId = className.replace("parent-","");
//If the parent is not checked, then check this parent
if (!$(pId).is(':checked'))
$(pId).attr('checked','checked');
}
//Is it NOT checked
else{
//Do other childs are not checked too?
//var className2 = $(this).attr('class');
//$(className2)
}
}
//If this is a parent, then check all childs
esle{
children.attr('checked', $(this).attr('checked'));
}
});
5
投票
我在这里为您编写代码:
var checkboxHandlerObj = {
init: function() {
$('#customerServices input:checkbox[class="parent"]').click(checkboxHandlerObj.parentClicked);
$('#customerServices input:checkbox[class^="parent-"]').click(checkboxHandlerObj.childClicked);
},
parentClicked: function() {
if ($(this).attr('checked')) {
$('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').attr('checked', 'checked');
} else {
$('#customerServices input:checkbox[class="parent-' + $(this).attr('id') + '"]').removeAttr('checked');
}
},
childClicked: function() {
var temp = $(this).attr('class').split('-');
var parentId = temp[1];
if ($(this).attr('checked')) {
$('#' + parentId).attr('checked', 'checked');
} else {
var atLeastOneEnabled = false;
$('#customerServices input:checkbox[class="' + $(this).attr('class') + '"]').each(function() {
if ($(this).attr('checked')) {
atLeastOneEnabled = true;
}
});
if (!atLeastOneEnabled) {
$('#' + parentId).removeAttr('checked');
}
}
}
};
checkboxHandlerObj.init();
Parent element
Child element
Child element
Parent element2
Child element2
Child element2
Parent element3
Parent element4
从-http://jsfiddle.net/PUWZX/4/
0
投票
我还没有检查所有脚本,但是请先告诉我是否将此代码放入
$(document).ready(function() {
....
});
并且jquery是否可以在您的页面上使用?
0
投票
尝试一下,http://jsfiddle.net/erick/dd6Qr/
// 1. Check all childs if parent is checked
$("#s9").change(function(){
if($(this).is(':checked')) {
var cls = '.parent-' + $(this).attr('id');
$(cls).attr('checked', true);
}
});
$('input[class*="parent"]').change(function(){
var cls = '.' + $(this).attr('class') + ':checked';
var len = $(cls).length;
var parent_id = '#' + $(this).attr('class').split('-')[1];
// 3. Check parent if at least one child is checked
if(len) {
$(parent_id).attr('checked', true);
} else {
// 2. Uncheck parent if all childs are unchecked.
$(parent_id).attr('checked', false);
}
});