Check first radio button with JQuery

拥有回忆 提交于 2019-12-03 22:08:57

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.

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

Andres

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

rahul

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!