我有一个分组列表的复选框.其中一些复选框可以出现在多个部分中.我想要做的是通过禁用用户选中复选框时所有相同的复选框,阻止用户在多个部分中选中相同的复选框.但是,他们选择的复选框不能被禁用,因此他们可以取消选中它(这也必须重新启用所有禁用的复选框,以便他们可以在其他部分中自由选择它,如果他们愿意的话)
有谁知道在JQuery中这样做的最佳方式?
示例代码:
<h3>Section 1</h3>
<ul>
<li>
<label for="section1_method_1">
<input name="method_1" value="43" id="section1_method_1" type="checkbox">Option 1
</label>
</li>
<li>
<label for="section1_method_2">
<input name="method_2" value="2" id="section1_method_2" type="checkbox">Option 2
</label>
</li>
<li>
<label for="section1_method_5">
<input name="method_5" value="6" id="section1_method_5" type="checkbox">Option 5
</label>
</li>
</ul>
<h3>Section 2</h3>
<ul>
<li>
<label for="section2_method_0">
<input name="method_0" value="5" id="section2_method_0" type="checkbox">Option 0
</label>
</li>
<li>
<label for="section2_method_1">
<input name="method_1" value="143" id="section2_method_1" type="checkbox">Option 1
</label>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
如您所见,选项1出现在第1部分和第2部分中.它们各自具有不同的ID,但名称相同.
我宁愿通过复选框来做,因为用户可能没有意识到他们在不同的部分选择了相同的选项,而如果复选框被禁用,他们会知道他们已经选择了它,如果他们想要改变他们的选择,他们会必须在物理上取消选中它.
我不会禁用复选框,我只是将它们绑定在一起,所以他们改变所有这样:
$('input[type=checkbox]').change(function(){
name = $(this).attr('name');
checked = $(this).attr('checked');
// this will set all the checkboxes with the same name to the same status
$('input[type=checkbox][name='+name+']').attr('checked',checked);
});?
Run Code Online (Sandbox Code Playgroud)
更新:要禁用其他复选框:
$('input[type=checkbox]').change(function(){
name = $(this).attr('name');
id = $(this).attr('id');
checked = $(this).attr('checked');
// disable all checkboxes except itself
$('input[type=checkbox][name='+name+']:not(#'+id+')')
.attr('disabled',checked);
});?
Run Code Online (Sandbox Code Playgroud)
更新2:灰显相应的标签:
$('input[type=checkbox]').change(function(){
name = $(this).attr('name');
id = $(this).attr('id');
checked = $(this).attr('checked');
$('input[type=checkbox][name='+name+']:not(#'+id+')')
.attr('disabled',checked)
.each(function(){
lid = $(this).attr('id'); // the id of the current disabled box
if (checked) {
$('label[for='+lid+']').addClass('disabled');
} else {
$('label[for='+lid+']').removeClass('disabled');
}
});
});?
Run Code Online (Sandbox Code Playgroud)
和一些CSS:
.disabled {
color: #888;
}
Run Code Online (Sandbox Code Playgroud)