如何取消选中单选按钮?

544

我有一组单选按钮,在使用jQuery提交AJAX表单后,希望将其取消选中状态。我有以下函数:

function clearForm(){
  $('#frm input[type="text"]').each(function(){
      $(this).val("");  
  });
  $('#frm input[type="radio":checked]').each(function(){
      $(this).checked = false;  
  });
 }

通过这个函数,我可以清除文本框中的值,但无法清除单选按钮中的值。

顺便说一下,我也尝试过 $(this).val(""); 但没有起作用。


3
你不需要使用"each"函数,你可以直接在jQuery对象上调用所需的函数。请参见下面的答案。 - James Wiseman
1
jQuery("input:radio").removeAttr("checked"); jQuery("input:radio").removeAttr("checked"); - Jitendra Damor
16个回答

841

要用纯JavaScript实现

this.checked = false;
或者 (jQuery)
$(this).prop('checked', false);
// Note that the pre-jQuery 1.6 idiom was
// $(this).attr('checked', false);

请参见jQuery prop() 帮助页面,了解 attr()prop() 之间的区别以及为什么现在推荐使用 prop()。
prop() 函数于2011年5月随 jQuery 1.6 引入。


29
请注意,1.6版本中他的行为将更倾向于使用prop(),而.attr()将被限制在实际属性上。 - Fabiano Soriani
1
这里最好使用纯JS吗? - Doug Molineux
15
@Pete:我想说的是,如果你已经使用了jQuery来构建系统,那么它还有一个额外的好处就是,如果将来有某个浏览器对这个系统的支持方式有所不同,你可以将浏览器支持的责任交给这个库来处理。但是,如果你的软件目前没有使用jQuery,那么只是为了这个目的而添加库是不值得的,因为它会增加额外的负担。 - David Hedlund
@David Hedlund:我想你是在暗示现在所有主流浏览器都以同样的方式处理这个问题,对吗? - Shawn
2
@qris:你的问题可能出在其他地方。使用jQuery 1.9的简单演示。在我的Chrome浏览器中肯定可以工作。 - David Hedlund
显示剩余2条评论

97
您不需要使用each函数。
$("input:radio").attr("checked", false);

或者

$("input:radio").removeAttr("checked");
同样的规则也应该适用于您的文本框:
$('#frm input[type="text"]').val("");

但是你可以改进这个

$('#frm input:text').val("");

2
.removeAttr 很可能会引起问题。 - Kzqai
可以详细说明一下吗?或者提供一个链接? - James Wiseman
是的,Kzqai,我也很好奇我的答案为什么会被踩。文档中没有提到任何风险。 - cjstehno
1
相关文档实际上在.prop()方法中:http://api.jquery.com/prop/ 引用:“属性通常会影响DOM元素的动态状态,而不会更改序列化的HTML属性。例如,输入元素的值属性、输入和按钮的禁用属性或复选框的选中属性。应该使用.prop()方法来设置禁用和选中,而不是.attr()方法。应该使用.val()方法来获取和设置值。” 这意味着... - Kzqai
1
这意味着.attr()将修改不同的底层源,而不是DOM的序列化HTML属性,虽然现在可能是兼容的(例如,当使用.attr()时,jQuery 1.9可能会同时修改两者),但不能保证在将.prop()作为规范时将来都会维护这种兼容性。例如,如果您使用.attr('checked', false);并且您使用的库包括.prop('checked', true);,那么就会存在固有的冲突,可能会导致烦人的错误。 - Kzqai

30

尝试

$(this).removeAttr('checked')

由于很多浏览器会将“checked = anything”解释为true,这将完全删除checked属性。

希望这可以帮到你。


另外,正如其他答案中提到的那样,您不需要使用each函数;您可以将removeAttr调用链接到选择器上。 - cjstehno
8
注意:这个回复是从2010年发出的。当时它是一种有效且被接受的方法。自那时以来,它已经过时。 - cjstehno

21

感谢Patrick,你让我的一天很美好!需要使用mousedown。不过,我已经改进了代码,这样就可以处理一组单选按钮。

//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
    //Capture radio button status within its handler scope,
    //so we do not use any global vars and every radio button keeps its own status.
    //This required to uncheck them later.
    //We need to store status separately as browser updates checked status before click handler called,
    //so radio button will always be checked.
    var isChecked;

    return function(event) {
        //console.log(event.type + ": " + this.checked);

        if(event.type == 'click') {
            //console.log(isChecked);

            if(isChecked) {
                //Uncheck and update status
                isChecked = this.checked = false;
            } else {
                //Update status
                //Browser will check the button by itself
                isChecked = true;

                //Do something else if radio button selected
                /*
                if(this.value == 'somevalue') {
                    doSomething();
                } else {
                    doSomethingElse();
                }
                */
            }
    } else {
        //Get the right status before browser sets it
        //We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
        isChecked = this.checked;
    }
}})());

21

在Igor的代码基础上稍作修改,根据Laurynas的插件来实现。这个修改可以适应与目标单选按钮相关联的可能的标签:

(function ($) {
    $.fn.uncheckableRadio = function () {

        return this.each(function () {
            var radio = this;
                $('label[for="' + radio.id + '"]').add(radio).mousedown(function () {
                    $(radio).data('wasChecked', radio.checked);
                });

                $('label[for="' + radio.id + '"]').add(radio).click(function () {
                    if ($(radio).data('wasChecked'))
                        radio.checked = false;
                });
           });
    };
})(jQuery);

1
这取决于标签的使用方式,如果它们使用ID,则此代码有效;如果单选按钮嵌套在标签中,则无效。您可以使用此更加增强的版本:https://gist.github.com/eikes/9484101 - eikes

20

将Igor的代码重写为插件。

用法:

$('input[type=radio]').uncheckableRadio();

插件:

(function( $ ){

    $.fn.uncheckableRadio = function() {

        return this.each(function() {
            $(this).mousedown(function() {
                $(this).data('wasChecked', this.checked);
            });

            $(this).click(function() {
                if ($(this).data('wasChecked'))
                    this.checked = false;
            });
        });

    };

})( jQuery );

如果我点击标签,取消选择不起作用。因此,虽然可以通过单击标签来选择收音机,但只有通过单击收音机按钮本身才能取消选择。 - Simon Hürlimann
@alkos333提供了一个似乎也适用于标签的解决方案。 - Simon Hürlimann
这取决于标签的使用方式,如果它们使用ID,则@alkos333的代码有效;如果单选按钮嵌套在标签中,请使用此版本:https://gist.github.com/eikes/9484101。 - eikes

18

对于单选框和单选框组:

$(document).ready(function() {
    $(document).find("input:checked[type='radio']").addClass('bounce');   
    $("input[type='radio']").click(function() {
        $(this).prop('checked', false);
        $(this).toggleClass('bounce');

        if( $(this).hasClass('bounce') ) {
            $(this).prop('checked', true);
            $(document).find("input:not(:checked)[type='radio']").removeClass('bounce');
        }
    });
});

14

试试这个,这会解决问题:

        $(document).ready(function() {
           $("input[type='radio']").mousedown(function(e) {
                if ($(this).attr("checked") == true) {
                   setTimeout("$('input[id=" + $(this).attr('id') + "]').removeAttr('checked');", 200);}
                else {
                    return true
                }
            });
        });

12

你也可以仅使用复选框来模拟单选按钮的行为:

<input type="checkbox" class="fakeRadio" checked />
<input type="checkbox" class="fakeRadio" />
<input type="checkbox" class="fakeRadio" />

那么,你可以使用这段简单的代码来为你工作:

$(".fakeRadio").click(function(){
    $(".fakeRadio").prop( "checked", false );
    $(this).prop( "checked", true );
});

它运行良好,您可以更好地控制每个按钮的行为。

您可以在以下网站进行尝试:http://jsfiddle.net/almircampos/n1zvrs0c/

这个分支还允许您取消选择所有内容,如评论中请求的一样:http://jsfiddle.net/5ry8n4f4/


这很棒,但是你不能取消所有的复选框。 - Stefan

12
尝试
$(this).attr("checked" , false );

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