Проверьте первый переключатель с помощью JQuery - PullRequest
29 голосов
/ 20 октября 2010

Я хотел бы проверить первую кнопку-переключатель в каждой группе.Но есть некоторые переключатели, которые отключены, поэтому скрипт должен их игнорировать и перейти к следующей не отключенной кнопке.

Я написал что-то подобное, но это не работает:

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

Большое спасибо

Ответы [ 6 ]

59 голосов
/ 20 октября 2010

Если ваши кнопки сгруппированы по их атрибуту имени, попробуйте:

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

Если они сгруппированы по родительскому контейнеру, то:

$("#parentId input:radio[disabled=false]:first").attr('checked', true);
17 голосов
/ 20 октября 2010
$("input:radio[name=groupX]:not(:disabled):first")

Это должно дать вам первый не отключенный переключатель из группы ...

8 голосов
/ 20 октября 2010

Ниже делает то, что вы хотите:

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

Демонстрация по адресу: JS Bin .

3 голосов
/ 20 октября 2010
<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/

2 голосов
/ 06 июня 2019

Я проверил первый ответ, и он не разрешает его.Я должен был использовать следующее предложение:

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

Это проверка первой видимой переключателя с именем = groupName

1 голос
/ 20 октября 2010

Попробуйте это:

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

Чтобы проверить первый переключатель только в группе, вы можете

 $("parentelement input:radio:not(:disabled):first-child").attr("checked", true);
...