JQuery - 根据值查找单选按钮

97

我该如何使用 JQuery 根据 value 值查找单选按钮?

5个回答

145

试试这个:

$(":radio[value=foobar]")

这将选择所有带有属性value="foobar"的单选按钮。


谢谢。我这样使用它: jQuery.each(cookieObj, function(i, val) { $(":radio[value=val]").attr('checked',true); }); - van
3
请尝试使用以下代码替换: function(i, val) { $(":radio[value="+val+"]").attr('checked',true); } - Gumbo
1
@Gumbo 如果我们给这个函数起一个名字,我们可以这样调用它吗?:$checkedRadioValues = findChecked("value"); - Ben Sewards

27

我正在使用jQuery 1.6,但这个并没有起作用:$(":radio[value=foobar]").attr('checked',true);

相反,我正在使用:$('[value="foobar"]').attr('checked',true);,它的效果很好。

实际上,我清除了收音机,并使用了prop而不是attr

$('[name=menuRadio]').prop('checked',false);

$('[name=menuRadio][value="Bar Menu"]').prop('checked',true);

这是一个已经修复的错误吗?还是我们仍然需要在值周围加上引号? - Simon_Weaver

19

这也可以通过这种方式实现:

$('input[type="radio"][value="aaa"]').val();

这将选择值为 aaa 的单选按钮


使用 .filter() 方法:

var radio =  $('input[type="radio"]').filter(function(){
                       return this.value === 'aaa';
                      }).val();

1
这将实际选择所有单选按钮并将它们的值更改为aaa,然后返回'aaa' - bendman

5

假设你的 HTML 中有以下内容:

<fieldset>
    <input type="radio" name="UI_opt" value="alerter" checked> Alerter<br/>
    <input type="radio" name="UI_opt" value="printer"> Printer<br/>
    <input type="radio" name="UI_opt" value="consoler"> Consoler<br/>
</fieldset>

那么这种事情就能够奏效。
$("fieldset input[name='UI_opt'][checked]").val()

2

完整的选择器应该是这样的:

bool shipToBilling = $("[name=ShipToBillingAddress][value=True]")

考虑到您可能有多个类似的单选按钮组

<input name="ShipToBillingAddress" type="radio" value="True" checked="checked">
<input name="ShipToBillingAddress" type="radio" value="False">

<input name="SomethingElse" type="radio" value="True" checked="checked">
<input name="SomethingElse" type="radio" value="False">

像这样使用ID选择器(下一个示例)是不好的,因为您不应该具有相同ID的多个元素。我假设发现这个问题的人已经知道这是不好的。
$("#DidYouEnjoyTheMovie:radio[value=yes]")

以下关于 :radio 的内容可能或者不可能引起兴趣。
因为 :radio 是 jQuery 的扩展,而不是 CSS 规范的一部分,使用 :radio 查询时无法利用本地 DOM querySelectorAll() 方法提供的性能提升。为了获得更好的性能,在现代浏览器中请使用 [type="radio"]。

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