How to set radio option checked onload with jQuery?
Need to check if no default is set and then set a default
How to set radio option checked onload with jQuery?
Need to check if no default is set and then set a default
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);
}
});
Note this behavior when getting radio input values:
$('input[name="myRadio"]').change(function(e) { // Select the radio input group
// This returns the value of the checked radio button
// which triggered the event.
console.log( $(this).val() );
// but this will return the first radio button's value,
// regardless of checked state of the radio group.
console.log( $('input[name="myRadio"]').val() );
});
So $('input[name="myRadio"]').val() does not return the checked value of the radio input, as you might expect -- it returns the first radio button's value.
This works for multiple radio buttons
$('input:radio[name="Aspirant.Gender"][value='+jsonData.Gender+']').prop('checked', true);