如何在 jQuery 中重置单选按钮,以便不选中任何单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/977137/
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-26 10:19:02  来源:igfitidea点击:

How to reset radiobuttons in jQuery so that none is checked

jqueryforms

提问by lambacck

I have radio buttons in HTML like this:

我在 HTML 中有这样的单选按钮:

<td>
    <input id="radio1" type="radio" name="correctAnswer" value="1">1</input>
    <input id="radio2" type="radio" name="correctAnswer" value="2">2</input>
    <input id="radio3" type="radio" name="correctAnswer" value="3">3</input>
    <input id="radio4" type="radio" name="correctAnswer" value="4">4</input>
</td>

This is in a form tag, and when user submits a form I want to make all the radio buttons back to the default. Meaning none of them checked.

这是在表单标签中,当用户提交表单时,我想让所有单选按钮恢复为默认值。这意味着他们都没有检查。

I have this code but it gives an error saying [0] is null or not an object

我有这个代码,但它给出了一个错误说 [0] is null or not an object

$('input[@name="correctAnswer"]')[0].checked = false;
$('input[@name="correctAnswer"]')[1].checked = false;
$('input[@name="correctAnswer"]')[2].checked = false;
$('input[@name="correctAnswer"]')[3].checked = false;

I am doing this in IE 6.

我在 IE 6 中这样做。

回答by lambacck

In versions of jQuery before 1.6 use:

在 1.6 之前的 jQuery 版本中使用:

$('input[name="correctAnswer"]').attr('checked', false);

In versions of jQuery after 1.6 you should use:

在 1.6 之后的 jQuery 版本中,您应该使用:

$('input[name="correctAnswer"]').prop('checked', false);

but if you are using 1.6.1+ you can use the first form (see note 2 below).

但如果您使用的是 1.6.1+,则可以使用第一种形式(请参阅下面的注释 2)。

Note 1:it is important that the second argument be falseand not "false"since "false"is not a falsy value. i.e.

注意 1:重要的是第二个参数为而不是“假”,因为“假”不是假值。IE

if ("false") {
    alert("Truthy value. You will see an alert");
}

Note 2:As of jQuery 1.6.0, there are now two similar methods, .attrand .propthat do two related but slightly different things. If in this particular case, the advice provide above works if you use 1.6.1+. The above will not work with 1.6.0, if you are using 1.6.0, you should upgrade. If you want the details, keep reading.

注2:在jQuery 1.6.0中,现在有两个类似的方法,.attr.prop认为做两个相关但略有不同的东西。如果在这种特殊情况下,如果您使用 1.6.1+,上面提供的建议有效。以上不适用于 1.6.0,如果您使用的是 1.6.0,您应该升级。如果您想要详细信息,请继续阅读。

Details:When working with straight HTML DOM elements, there are properties attached to the DOM element (checked, type, value, etc) which provide an interface to the running state of the HTML page. There is also the .getAttribute/.setAttributeinterface which provides access to the HTML Attribute values as provided in the HTML. Before 1.6 jQuery blurred the distinction by providing one method, .attr, to access both types of values. jQuery 1.6+ provides two methods, .attrand .propto get distinguish between these situations.

详细说明:当与直HTML DOM元素工作,有附着在DOM元素(属性checkedtypevalue等),其提供到HTML页面的运行状态的接口。还有.getAttribute/.setAttribute接口可以访问 HTML 中提供的 HTML 属性值。在 1.6 之前,jQuery 通过提供一种方法.attr来访问两种类型的值,从而模糊了这种区别。jQuery的1.6 +提供了两种方法,.attr.prop得到这些情况加以区分。

.propallows you to set a property on a DOM element, while .attrallows you to set an HTML attribute value. If you are working with plain DOM and set the checked property, elem.checked, to trueor falseyou change the running value (what the user sees) and the value returned tracks the on page state. elem.getAttribute('checked')however only returns the initial state (and returns 'checked'or undefineddepending on the initial state from the HTML). In 1.6.1+ using .attr('checked', false)does both elem.removeAttribute('checked')and elem.checked = falsesince the change caused a lot of backwards compatibility issues and it can't really tell if you wanted to set the HTML attribute or the DOM property. See more information in the documentation for .prop.

.prop允许您在 DOM 元素上设置属性,同时.attr允许您设置 HTML 属性值。如果您正在使用纯 DOM 并将检查属性设置为elem.checked,true或者false您更改运行值(用户看到的),并且返回的值会跟踪页面状态。elem.getAttribute('checked')然而只返回初始状态(并返回'checked'undefined取决于来自 HTML 的初始状态)。在 1.6.1+ 中使用.attr('checked', false)两者都可以,elem.removeAttribute('checked')并且elem.checked = false由于更改导致了很多向后兼容性问题,并且它无法真正判断您是要设置 HTML 属性还是 DOM 属性。在.prop文档中查看更多信息。

回答by Benjk

The best way to set radiobuttons state in jquery:

在 jquery 中设置单选按钮状态的最佳方法:

HTML:

HTML:

<input type="radio" name="color" value="orange" /> Orange 
<input type="radio" name="color" value="pink" /> Pink 
<input type="radio" name="color" value="black" /> Black
<input type="radio" name="color" value="pinkish purple" /> Pinkish Purple

Jquery (1.4+) code to pre-select one button :

用于预选一个按钮的 Jquery (1.4+) 代码:

var presetValue = "black";
$("[name=color]").filter("[value='"+presetValue+"']").attr("checked","checked");

In Jquery 1.6+ code the .prop() method is preferred :

在 Jquery 1.6+ 代码中,首选 .prop() 方法:

var presetValue = "black";
$("[name=color]").filter("[value='"+presetValue+"']").prop("checked",true);

To unselect the buttons :

要取消选择按钮:

$("[name=color]").removeAttr("checked");

回答by bdukes

Your problem is that the attribute selector doesn't start with a @.

您的问题是属性选择器不是以@.

Try this:

尝试这个:

$('input[name="correctAnswer"]').attr('checked', false);

回答by Waqas Ali Khan Puar

$('#radio1').removeAttr('checked');
$('#radio2').removeAttr('checked');
$('#radio3').removeAttr('checked');
$('#radio4').removeAttr('checked');

Or

$('input[name="correctAnswer"]').removeAttr('checked');

回答by vv-reflex

Finally after a lot of tests, I think the most convenient and efficient way to preset is:

最后经过大量测试,我认为最方便有效的预设方式是:

var presetValue = "black";
$("input[name=correctAnswer]").filter("[value=" + presetValue + "]").prop("checked",true);
$("input[name=correctAnswer]").button( "refresh" );//JQuery UI only

The refresh is required with the JQueryUI object.

JQueryUI 对象需要刷新。

Retrieving the value is easy :

检索值很容易:

alert($('input[name=correctAnswer]:checked').val())

Tested with JQuery 1.6.1, JQuery UI 1.8.

使用 JQuery 1.6.1、JQuery UI 1.8 进行测试。

回答by Nielsvh

I know this is old and that this is a little off topic, but supposing you wanted to uncheck only specific radio buttons in a collection:

我知道这是旧的,这有点偏离主题,但假设您只想取消选中集合中的特定单选按钮:

$("#go").click(function(){
    $("input[name='correctAnswer']").each(function(){
      if($(this).val() !== "1"){
        $(this).prop("checked",false);
      }
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>
<input type="button" id="go" value="go">

And if you are dealing with a radiobutton list, you can use the :checked selector to get just the one you want.

如果你正在处理一个单选按钮列表,你可以使用 :checked 选择器来获得你想要的。

$("#go").click(function(){
  $("input[name='correctAnswer']:checked").prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>
<input type="button" id="go" value="go">

回答by Adeel Raza Azeemi

Although prop changed the checked status but change also show that in the form.

虽然 prop 改变了选中状态,但改变也显示在表单中。

$('input[name="correctAnswer"]').prop('checked', false).change();

回答by elzaer

If you want to clear all radio buttons in the DOM:

如果要清除 DOM 中的所有单选按钮:

$('input[type=radio]').prop('checked',false);

$('input[type=radio]').prop('checked',false);

回答by Lakshmana Kumar D

<div id="radio">
<input type="radio" id="radio1" name="radio"/><label for="radio1">Bar Chart</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Pie Chart</label>
<input type="radio" id="radio3" name="radio"/><label for="radio3">Datapoint Chart</label>
</div>

$('#radio input').removeAttr('checked');
// Refresh the jQuery UI buttonset.                  
$( "#radio" ).buttonset('refresh');

回答by sonali

Radio button set checked through jquery:

通过jquery检查的单选按钮集:

<div id="somediv" >
 <input type="radio" name="enddate" value="1"  />
 <input type="radio" name="enddate" value="2"  />
 <input type="radio" name="enddate" value="3"  />
</div>

jquery code:

jQuery代码:

$('div#somediv input:radio:nth(0)').attr("checked","checked");