使用jQuery取消选中所有复选框,然后选中单击的复选框 [英] using jQuery to uncheck all checkboxes and then check the clicked one

查看:98
本文介绍了使用jQuery取消选中所有复选框,然后选中单击的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

      <div class="pricing-levels-2">
        <p>Which level would you like? (Click all that apply)</p>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 1<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 4<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 5<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 6<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 7<br>
      </div>
      <div class="pricing-levels-3">
        <p>Which level would you like? (Click all that apply)</p>
        <input class="single-checkbox"type="checkbox" name="vehicle" value="Bike">Level 1<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 2<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Bike">Level 3<br>
      </div>

我希望每次单击其中一个时都清除.pricing-levels-2复选框,所以我做到了:

I want the .pricing-levels-2 checkboxes to clear each time I click in one of them, so I did:

jQuery('.pricing-levels-2 .single-checkbox').on('click', function(){
  jQuery('.pricing-levels-2 .single-checkbox').attr('checked', false);
  jQuery(this).attr('checked', true);
});

但是问题是现在所有的复选框都清除了,即使我正在选择的复选框也是如此.因此,我无法选择任何一个(我希望选择要单击的那个).

But the problem is that now ALL the checkboxes clear, even the one I'm selecting. So I can't select any (I want the one I'm clicking to be selected).

我做错了什么?

推荐答案

您需要使用 .prop 代替:

jQuery('.pricing-levels-2 .single-checkbox').on('click', function(){
  jQuery('.pricing-levels-2 .single-checkbox').prop('checked', false);
  jQuery(this).prop('checked', true);
});

这篇关于使用jQuery取消选中所有复选框,然后选中单击的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆