使用Jquery取消选中单选按钮的帮助

4

我需要帮助来取消或选中同一个单选按钮,如果该按钮已经被选中?我有一个jQuery函数,用于启用或禁用其他单选按钮,如果已经被选中,现在我想添加一些功能,用于选中或取消选中同一个单选按钮。

(function ($) {
  $(document).ready(function () {
    $('input:radio').click(function(){
      var $inputs = $('input:radio')

      if($(this).is(':checked')){
        $inputs.not(this).prop('disabled',true);
      }else{
        $inputs.prop('disabled',false); 
      }
    })

  });
})(jQuery);

<input type="radio" value="Test1" />Test1
<input type="radio" value="Test2" />Test2
<input type="radio" value="Test1" />Test1
<input type="radio" value="Test2" />Test2

这背后的使用案例是什么?也许你只是想在每次显示页面时重置单选按钮的状态? - Mobiletainment
5个回答

5
尽管回答已经太晚了,但它可以帮助其他人
我尝试了这个解决方案。
对我来说效果非常好!
$("input[type='radio'].myClass").click(function(){
        var $self = $(this);
        if ($self.attr('checkstate') == 'true')
        {
            $self.prop('checked', false);
            $self.each( function() {
                $self.attr('checkstate', 'false');
            })  
        }
        else
        {
            $self.prop('checked', true);
            $self.attr('checkstate', 'true');
            $("input[type='radio'].myClass:not(:checked)").attr('checkstate', 'false');
        }
})

永远不晚!谢谢分享! - Fabiano Shark

2

只需将disabled替换为checked

$input.prop("checked", false);

或者对于this元素:

this.checked = false;

然而,如果你正在寻找可以选中和取消选中的表单元素,也许 input type="checkbox" /> 是你需要的。


你指的是这一行代码 if($(this).is(':checked')) 的意思是什么? - user2249079
所以根据逻辑,你应该使用类似于 this.checked = !this.checked 的东西。 - VisioN

0
$inputs.filter(':checked').prop('checked', false);

0

我认为你需要使用复选框而不是单选按钮来取消已选中的选项:

<input class="checkDisable" type="checkbox" value="Test1" />Test1
<input class="checkDisable" type="checkbox" value="Test2" />Test2
<input class="checkDisable" type="checkbox" value="Test3" />Test3
<input class="checkDisable" type="checkbox" value="Test4" />Test4


(function ($) {
$(document).ready(function () {
 $('input:checkbox.checkDisable').change(function(){
    var $inputs = $('input:checkbox.checkDisable')
    if($(this).is(':checked')){
        $inputs.not(this).prop('disabled',true);
    }else{
        $inputs.prop('disabled',false); 
        $(this).prop('checked',false);
    }
 })

});
})(jQuery);

Mohamed Ali,我在页面中已经有其他复选框了,所以如果我再次使用jQuery复选框,就会出现问题。 - user2249079
@edgematrix,这很简单,为您指定的复选框添加类名,然后使用此类选择复选框。 - Mohamed AbdElRazek

0

Pablo Araya的答案很好,但是...

$self.prop('checked', true);

在这里是多余的。每次点击时,单选按钮已经有一个已选择的状态。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接