问题
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
回答1:
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);
回答2:
$("input:radio[name=groupX]:not(:disabled):first")
This should give you the first non-disabled radio-button from a group...
回答3:
The below does what you want:
$(document).ready(
function(){
$('input:radio:first-child').attr('checked',true);
}
);
Demo at: JS Bin.
回答4:
<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/
回答5:
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
回答6:
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);
来源:https://stackoverflow.com/questions/3977699/check-first-radio-button-with-jquery