Jquery 如何启用/禁用另一个复选框旁边的复选框?
如果我选中左复选框之一,我希望它旁边的复选框将被启用。如果我取消选中其中一个左侧复选框,则应再次禁用它旁边的复选框: $'input[type=checkbox]'。changefunction{ $input:复选框:选中:not.delivery.eachfunction{ 如果$input:复选框:选中。长度>0{ $this.closesttr.children'.disable'.removeAttrIsabled; }否则{ $this.closesttr.children'.disable'.addAttrdisabled; } }; };Jquery 如何启用/禁用另一个复选框旁边的复选框?,jquery,checkbox,Jquery,Checkbox,如果我选中左复选框之一,我希望它旁边的复选框将被启用。如果我取消选中其中一个左侧复选框,则应再次禁用它旁边的复选框: $'input[type=checkbox]'。changefunction{ $input:复选框:选中:not.delivery.eachfunction{ 如果$input:复选框:选中。长度>0{ $this.closesttr.children'.disable'.removeAttrIsabled; }否则{ $this.closesttr.children'.di
如果您可以将第一个复选框和第二个复选框分别设置为不同的类,则会更容易,即:
<tr>
<td><input class="checkbox-parent" type="checkbox"></td>
<td><input class="checkbox-child disable" disabled="" type="checkbox"></td>
</tr>
您不应该使用.removeAttr甚至使用.attr来操作布尔属性,例如选中、选中、多个、禁用等
如果无法更改标记
或者,如果您的标记无法更改,则可以在表行中选择第一个使用或和第二个/最后一个复选框use.eq1表示第二个,最后一个
请注意,这不是最好的解决方案,因为对标记的更改将意味着您必须修改这些硬编码的魔法常量和逻辑
// Bind change event to the FIRST checkbox
$('tr input[type="checkbox"]').first().change(function() {
// Get the SECOND checkbox
var $child = $(this).closest('tr').find('input[type="checkbox"]').eq(1);
// If you want to get the LAST checkbox, use:
// var $child = $(this).closest('tr').find('input[type="checkbox"]').last();
// Update child state based on checked status
// - set disabled to false when is checked
// - set disabled to true when is unchecked
$child.prop('disabled', !this.checked);
});
您的标记也有一些问题需要解决:
您必须将标记封装在一个元素中,否则浏览器将从标记中取出所有表元素,以使其在语义上正确
不是的有效直接子级
请参见此处的更新代码:
$'.checkbox parent'.changefunction{
//遍历DOM以获取关联的子复选框
var$child=$this.closest'tr'.find'.checkbox child';
//基于选中状态更新子状态
$child.prop'disabled',!this.checked;
};
另一个使用现有标记的解决方案是,我们可以将更改事件附加到DOM就绪上启用的复选框 在更改事件中,获取行中所有复选框的列表,排除单击的当前复选框,然后根据当前复选框选择更改另一个复选框的禁用属性 $function{ $输入[类型=复选框]:已启用.changefunction{ $this.closesttr.findinput:checkbox.notthis.attr'disabled',!this.checked }; }
给你一个解决方案 $'input[type=checkbox]'。在'change',函数{ 如果$this.is':选中'{ $this.closest'td'。next'td'。查找'input[class=disable]'。removeAttr'disabled'; }否则{ $this.closest'td'。下一个'td'。查找'input[class=disable]'。属性'disabled','disabled'; } };
// Bind change event to the FIRST checkbox
$('tr input[type="checkbox"]').first().change(function() {
// Get the SECOND checkbox
var $child = $(this).closest('tr').find('input[type="checkbox"]').eq(1);
// If you want to get the LAST checkbox, use:
// var $child = $(this).closest('tr').find('input[type="checkbox"]').last();
// Update child state based on checked status
// - set disabled to false when is checked
// - set disabled to true when is unchecked
$child.prop('disabled', !this.checked);
});