Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 775
Matthew Avatar asked Oct 20 '10 12:10

Matthew


People also ask

How do you checked radio in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.

How do I select the first radio button as default?

To select a radio button by default we have to check it as true. If it is checked as true then by default it will be autofocused. In the following example, we have only radio buttons and none of them is autofocused.

How do I get the first radio button in CSS?

The simplest way is to use the :first-child selector. As opposed to :first , which only returns the first of the matched elements, :first-child will return any element that is the first child of its parent element: //returns the first radio button in group1, and the first one in group2 as well.


2 Answers

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); 
like image 185
sje397 Avatar answered Sep 22 '22 14:09

sje397


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

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

like image 36
Šime Vidas Avatar answered Sep 18 '22 14:09

Šime Vidas