How to set radio option checked onload with jQuery?
Need to check if no default is set and then set a default
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.
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.
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); } });
How about a one liner?
$('input:radio[name="gender"]').filter('[value="Male"]').attr('checked', true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With