How would I use JQuery to开发者_如何学Go find a radio button by its value?
Try this:
$(":radio[value=foobar]")
This will select all radio buttons with the attribute value="foobar"
.
I'm using jQuery 1.6 and this did not work for me: $(":radio[value=foobar]").attr('checked',true);
Instead, I'm using: $('[value="foobar"]').attr('checked',true);
and it works great.
The actual code I'm using clears the radios first and uses prop
instead of attr
$('[name=menuRadio]').prop('checked',false);
$('[name=menuRadio][value="Bar Menu"]').prop('checked',true);
This can be achieved by this too:
$('input[type="radio"][value="aaa"]').val();
This will select the radio which has the value of aaa
With .filter()
method:
var radio = $('input[type="radio"]').filter(function(){
return this.value === 'aaa';
}).val();
say you have something like this in the 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>
then this sort of thing works.
$("fieldset input[name='UI_opt'][checked]").val()
A full selector would look like this:
bool shipToBilling = $("[name=ShipToBillingAddress][value=True]")
given that you probably have more than one radio button group like this
<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">
Using an ID selector like this (next example) is bad because you shouldn't have multiple elements with the same ID. I assume someone finding this question already knows this is bad.
$("#DidYouEnjoyTheMovie:radio[value=yes]")
The following about :radio
may or may not be of interest
Because :radio is a jQuery extension and not part of the CSS specification, queries using :radio cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use [type="radio"] instead.
精彩评论