Pergunta

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 button.

I wrote something like this but it doesn't work:

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

Thanks a lot

Foi útil?

Solução

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);

Outras dicas

$("input:radio[name=groupX]:not(:disabled):first")

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

The below does what you want:

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

Demo at: JS Bin.

<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/

I tested the first answer and it doesn't resolve it. I had to use the following sentence:

jQuery("input:radio[name=groupName]:visible")[0].checked=true;

This check the first visible radio button with name = groupName

Try this :

 $("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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top