NinjaCat
NinjaCat

Reputation: 10194

How to select nested radiobutton with jQuery?

I have the following code:

<form class="form-inline" id="myform0">    
    <fieldset>                  
        <label class="radio"><input type="radio" name="optionsRadios" id="optionHere2" value="2">Yes</label>
        <label class="radio"><input type="radio" name="optionsRadios" id="optionHere1" value="1">No</label>            
        <label class="radio"><input type="radio" name="optionsRadios" id="optionHere3" value="3">Not decided</label>                        
    </fieldset>                 
</form>
<form class="form-inline" id="myform1">    
    <fieldset>                  
        <label class="radio"><input type="radio" name="optionsRadios" id="optionHere2" value="2">Yes</label>
        <label class="radio"><input type="radio" name="optionsRadios" id="optionHere1" value="1">No</label>            
        <label class="radio"><input type="radio" name="optionsRadios" id="optionHere3" value="3">Not decided</label>                        
    </fieldset>                 
</form>

What I want to do is be able to programatically select a radio button in each group. Everything I tried so far has not worked. Thoughts?

Edit:

This selects all of them: $("input[name=optionsRadios][value=1]").attr('checked', 'checked');

I am just looking to select a specific one.

Upvotes: 0

Views: 1077

Answers (1)

VisioN
VisioN

Reputation: 145368

To check each first radio button use the following code:

$("form").each(function() {
    $(this).find(":radio:first").prop("checked", true);
});

Or shorter:

$("form").find(":radio:first").prop("checked", true);​​​​​​​​​​​​​​​​

Also check you have elements with the same IDs (e.g. optionHere1, optionHere2, etc).

ID's should be unique!

DEMO: http://jsfiddle.net/mAeTa/


UPDATE. This will also work fine:

$("form").find(":radio[name='optionsRadios'][value='1']").prop("checked", true);​

DEMO: http://jsfiddle.net/mAeTa/1/

Upvotes: 4

Related Questions