【问题标题】:How to disable or inactive checkbox when select current in jQuery在jQuery中选择当前时如何禁用或非活动复选框
【发布时间】:2020-01-01 07:30:38
【问题描述】:

当当前复选框被选中或选中时,我想禁用其他复选框。

以下是我的代码。我试过了,但是不行

HTML

<input type="checkbox" name="test" id="test" class="test">One
<input type="checkbox" name="test" id="test" class="test">Two
<input type="checkbox" name="test" id="test" class="test">Three
<input type="checkbox" name="test" id="test" class="test">Four
<input type="checkbox" name="test" id="test" class="test">Five

JQuery 脚本

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){

        $(".test").each(function(){
            if($(this).is(':checked')){
                $(this).prop('checked',true);
                $('.test').prop('checked',false);
            }
        })
    })  
</script>

【问题讨论】:

  • 不要使用重复的ID!

标签: javascript jquery html checkbox


【解决方案1】:

您可以使用change 事件处理程序并读取所单击复选框的:checked 值。根据:checked值禁用或启用其他复选框

见下面的代码

注意:始终为所有 HTML 元素使用唯一的 id,否则使用 id 选择器的 jquery 脚本会得到错误的结果

$(document).ready(function(){
        $(".test").on('change', function(){
           $('.test').not(this).prop('disabled', $(this).is(':checked'));
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="test" id="test1" class="test">One
<input type="checkbox" name="test" id="test2" class="test">Two
<input type="checkbox" name="test" id="test3" class="test">Three
<input type="checkbox" name="test" id="test4" class="test">Four
<input type="checkbox" name="test" id="test5" class="test">Five

【讨论】:

    【解决方案2】:

    首先你需要使用clickchange事件,然后你不需要使用$(this).prop('checked',true);并且不要使用重复的id

    $('.test').click(function() {
      let $this = $(this);
      if ($this.is(':checked')) {
        $('.test').not($this).attr('disabled', true)
      } else {
        $('.test').attr('disabled', false)
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label><input type="checkbox" name="test" class="test">One</label>
    <label><input type="checkbox" name="test" class="test">Two</label>
    <label><input type="checkbox" name="test" class="test">Three</label>
    <label><input type="checkbox" name="test" class="test">Four</label>
    <label><input type="checkbox" name="test" class="test">Five</label>

    要制作disable,您需要使用'disabled', true

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 2020-06-22
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多