Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set radio option checked onload with jQuery

How to set radio option checked onload with jQuery?

Need to check if no default is set and then set a default

like image 889
Phill Pafford Avatar asked May 15 '09 22:05

Phill Pafford


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 you check the radio button is checked or not in Javascript?

Use document. getElementById('id'). checked method to check whether the element with selected id is check or not. If it is checked then display its corresponding result otherwise check the next statement.


2 Answers

Say you had radio buttons like these, for example:

    <input type='radio' name='gender' value='Male'>     <input type='radio' name='gender' value='Female'> 

And you wanted to check the one with a value of "Male" onload if no radio is checked:

    $(function() {         var $radios = $('input:radio[name=gender]');         if($radios.is(':checked') === false) {             $radios.filter('[value=Male]').prop('checked', true);         }     }); 
like image 115
Paolo Bergantino Avatar answered Oct 03 '22 21:10

Paolo Bergantino


How about a one liner?

$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true); 
like image 39
Andrew McCombe Avatar answered Oct 03 '22 20:10

Andrew McCombe