莫菲    

jquery checkbox 实现选中一个后其余disabled,没有选中时所有可选

7年前发布  · 1599 次阅读
  jquery 

因为该用单选按钮的地方 非要用多选框,只能找这样的方法实现单选的效果。。。。。。

基础:

html

<input type="checkbox" class="optionBox" value="1" >
<input type="checkbox" class="optionBox" value="2">
<input type="checkbox" class="optionBox"  value="3">
<input type="checkbox" class="optionBox" value="4">
jquery

  <script>
        $(document).ready(function(){
            $(".optionBox").click(function(){
                var $checkbox = $(this);
                var isChecked = $checkbox.is(':checked');

                //If no option is checked, the make all the options available to be selected
                //Otherwise, one option must be checked so lock out all other options
                if(isChecked)
                    $checkbox.siblings(":checkbox").attr("disabled", "disabled");
                else
                    $checkbox.siblings(":checkbox").removeAttr("disabled");
            });
        });
    </script>

在<table>中,一个<tr>中的多选框只能选择一个:

html

<table>
    <tr>
        <td><input type="checkbox" class="optionBox" value="11" ></td>
        <td><input type="checkbox" class="optionBox" value="12" ></td>
        <td><input type="checkbox" class="optionBox" value="13" ></td>
        <td><input type="checkbox" class="optionBox" value="14" ></td>
    </tr>
    <tr>
        <td><input type="checkbox" class="optionBox" value="21" ></td>
        <td><input type="checkbox" class="optionBox" value="22" ></td>
        <td><input type="checkbox" class="optionBox" value="23" ></td>
        <td><input type="checkbox" class="optionBox" value="24" ></td>
    </tr>
</table>
js

    <script>
        $(document).ready(function(){
            $(':checkbox').on('change',function() {
                var checked = this.checked;
                $(this).closest('tr').find(':checkbox').not(this).prop('disabled',checked);
            });
        });
    </script>

在<table>中一个table中只能选择一个:

html

<table>
    <tr>
        <td><input type="checkbox" class="optionBox" value="11" ></td>
        <td>1</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="optionBox" value="21" ></td>
        <td>2</td>
    </tr>
</table>
js

<script>
        $(document).ready(function(){
            $(':checkbox').on('change',function() {
                var checked = this.checked;
                $(this).closest('table').find(':checkbox').not(this).prop('disabled',checked);
            });
        });
</script>