使用jQuery单击时使单选按钮取消选中自身

时间:2018-09-03 21:16:42

标签: jquery radio-button uncheck

对于一组选中了第2个(共3个)选项的单选按钮,如何在单击选中的选项时使其不选中(与取消选中复选框相同的行为)?

1 个答案:

答案 0 :(得分:1)

尝试添加虚拟单选选项并使用display:none将其隐藏

<form>
   <input type="radio" name="gender" value="male" checked> Male<br>
   <input type="radio" name="gender" value="female"> Female<br>
   <input type="radio" name="gender" style="display:none" value="other">
</form>

那么您的JS应该是:

var currentValue;
  $('form>input').click(function(){
    if(currentValue===$(this).val())     {
      $(this).parent().find('input:last-child').click();
      currentValue=$(this).parent().find('input:last-child').val();
    }
    else{
      currentValue=$(this).val()
    }
  });

在JS中,我们检查点击是否在实际选中的选项上,如果是,它会选择虚拟选项,以便收音机在视觉上“取消选中”。希望对您有帮助。

相关问题