单击具有类似类的复选框时,禁用其他复选框

disable other checkboxes when one with similar class is clicked

本文关键字:复选框 其他 单击      更新时间:2023-09-26

一旦选中其中一个复选框,我就需要禁用同一类的其余复选框。

$('.Cat .RoleChk').change(function(){
    if($(this).is(':checked')){
$('.Cat .RoleChk').attr('disabled',true);
    $(this).attr('disabled','');
}
else{
$('.Cat .RoleChk').attr('disabled','');
}
});

<div class="Cat" style="width: 155px; float: left">
        <p>Employee Role</p>     
        <input class="RoleChk" name="Role" type="checkbox" value="OfficeEmployee"/>&nbsp;Office Employee<br/>
        <input class="RoleChk" name="Role" type="checkbox" value="Marketer"/>&nbsp;Marketer<br/>
        <input class="RoleChk" name="Role" type="checkbox" value="ProjectManager"/>&nbsp;Project Manager<br/>
    </div>
    <div class="Cat" style="width: 155px; float: left">
        <p>Groups</p>
        <input class="GrpChk" name="Group" type="checkbox" value="Aviation"/>&nbsp;Aviation<br/>
        <input class="GrpChk" name="Group" type="checkbox" value="Electrical"/>&nbsp;Electrical<br/>
        <input class="GrpChk" name="Group" type="checkbox" value="Mining"/>&nbsp;Mining
    </div>

怎么样:

$(".RoleChk, .GrpChk").change(function() {
    this.checked ? $("." + this.className).not(this).prop("disabled", true) : $("." + this.className).not(this).prop("disabled", false);
});

演示:http://jsfiddle.net/tymeJV/96Wvq/1/

我保留了选中的原始复选框,这允许用户取消选中并重新启用。如果要删除此功能,请从三进制中取出.not(this)

<script>
jQuery(document).ready(function(){
    $('.Cat .RoleChk').change(function(){
        if($(this).is(':checked')){
            $('.Cat .RoleChk').attr('disabled',true);
            $(this).removeAttr("disabled");
        }
        else{
            $('.Cat .RoleChk').removeAttr("disabled");
        }
    });
});
</script>