开发者

Check first radio button with JQuery

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 but开发者_高级运维ton.

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


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


$("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.


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


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


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


A little upgrade for 2020. The official documentation suggests the use of "first()" and "prop()"

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


This makes the first radio checked by default

jQuery("input:radio[name=groupName]").first().click()


If you've the class and you don't bother about disabled items, just do this

$(".className").first().click();

Or simply

$(".className").first().prop("checked", true);


$('.choose_site input:radio').attr('checked',false); //Unchecked All
$('.choose_site input:radio').first().prop("checked", true); // Checked First
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜