Javascript 如何取消选中单选按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2117538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:48:57  来源:igfitidea点击:

How to uncheck a radio button?

javascriptjqueryradio-buttondynamic-forms

提问by systemsfault

I have group of radio buttons that I want to uncheck after an AJAX form is submitted using jQuery. I have the following function:

我有一组单选按钮,我想在使用 jQuery 提交 AJAX 表单后取消选中它们。我有以下功能:

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

With the help of this function, I can clear the values at the text boxes, but I can't clear the values of the radio buttons.

借助此功能,我可以清除文本框中的值,但无法清除单选按钮的值。

By the way, I also tried $(this).val("");but that didn't work.

顺便说一句,我也试过,$(this).val("");但没有奏效。

回答by dxh

either (plain js)

要么(纯js)

this.checked = false;

or (jQuery)

或 (jQuery)

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

See jQuery prop() help pagefor an explanation on the difference between attr()and prop()and why prop() is now preferable.
prop() was introduced with jQuery 1.6 in May 2011.

有关attr()prop()之间的区别以及为什么现在更可取的原因,请参阅jQuery prop() 帮助页面。 prop() 于 2011 年 5 月在 jQuery 1.6 中引入。

回答by James Wiseman

You wouldn't need the eachfunction

你不需要这个each功能

$("input:radio").attr("checked", false);

Or

或者

$("input:radio").removeAttr("checked");

The same should also apply to your textbox:

这同样适用于您的文本框:

$('#frm input[type="text"]').val("");

But you could improve this

但你可以改进这一点

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

回答by cjstehno

Try

尝试

$(this).removeAttr('checked')

Since a lot of browsers will interpret 'checked=anything' as true. This will remove the checked attribute altogether.

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

Hope this helps.

希望这可以帮助。

回答by alkos333

Slight modification of Laurynas' plugin based on Igor's code. This accommodates possible labels associated with the radio buttons being targeted:

基于 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);

回答by igor

Thanks Patrick, you made my day! It's mousedown you have to use. However I've improved the code so you can handle a group of radio buttons.

谢谢帕特里克,你让我开心!这是您必须使用的 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;
    }
}})());

回答by Laurynas

Rewrite of Igor's code as plugin.

将 Igor 的代码重写为插件。

Use:

用:

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

Plugin:

插入:

(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 );

回答by Sylvain Kocet

For radio and radio group:

对于广播和广播组:

$(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');
        }
    });
});

回答by Patrick Rietveld

Try this, this will do the trick:

试试这个,这可以解决问题:

        $(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
                }
            });
        });

回答by rahul

Try

尝试

$(this).attr("checked" , false );

回答by Almir Campos

You can also simulate the radiobutton behavior using only checkboxes:

您还可以仅使用复选框来模拟单选按钮行为:

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

Then, you can use this simple code to work for you:

然后,您可以使用这个简单的代码来为您工作:

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

It works fine and you have more control over the behavior of each button.

它工作正常,您可以更好地控制每个按钮的行为。

You can try it by yourself at: http://jsfiddle.net/almircampos/n1zvrs0c/

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

This fork also let's you unselect all as requested in a comment: http://jsfiddle.net/5ry8n4f4/

这个叉子还让你根据评论中的要求取消选择所有内容:http: //jsfiddle.net/5ry8n4f4/