views:

70

answers:

5

Hello, I would like to check the first radio button of each group. But there are some radio button that are disabled, so the script should ignore them and go to next non disabled.

I write something like this but doesn't work:

$(document).ready(function(){
if ($("input['radio']).is(':disabled'))
    {  
        $(this).attr('checked', false );
    }
else
    {
        $(this).attr('checked', true );
    }
});

Thanks a lot

A: 
 $("input:radio:not(:disabled)).attr("checked", true);

To check the first radio button only in a group you can

 $("parentelement input:radio:not(:disabled):first-child").attr("checked", true);
rahul
I believe the OP meant "group" as in "all radio buttons that share the same name attribute"
Šime Vidas
`first-child` isn't right
sje397
+1  A: 

The below does what you want:

$(document).ready(
  function(){
    $('input:radio:first-child').attr('checked',true);
  }
  );

Demo at: JS Bin.

David Thomas
Although, to be fair, both @Šime and @rahul provide for sensible sanity-checks.
David Thomas
`first-child` isn't right
sje397
+3  A: 
$("input:radio[name=groupX]:not(:disabled):first")

This should give you the first non-disabled radio-button from a group...

Šime Vidas
A: 

If your buttons are grouped by their name attribute, try:

$("input:radio[name=groupName][disabled=false]:first").attr('checked', true);

If they are grouped by a parent container, then:

$("#parentId input:radio[disabled=false]:first").attr('checked', true);
sje397
A: 
<input type="radio" name="r1"><br>
<input type="radio" name="r1"><br>
<hr>
<input type="radio" name="r2"><br>
<input type="radio" name="r2"><br>
<input type="radio" name="r2"><br>

<script>
$(function(){
    //removed duplicates form the following array
    $(jQuery.unique(
        //create an array with the names of the groups
        $('INPUT:radio')
            .map(function(i,e){
                return $(e).attr('name') }
            ).get()
    ))
    //interate the array (array with unique names of groups)
    .each(function(i,e){
        //make the first radio-button of each group checked
        $('INPUT:radio[name="'+e+'"]:visible:first')
            .attr('checked','checked');
    });
});
</script>

jsfiddle = http://jsfiddle.net/v4auT/

Floyd