I try to check a radio button with jQuery. Here's my code:
<form> <div id='type'> <input type='radio' id='radio_1' name='type' value='1' /> <input type='radio' id='radio_2' name='type' value='2' /> <input type='radio' id='radio_3' name='type' value='3' /> </div> </form>
And the JavaScript:
jQuery("#radio_1").attr('checked', true);
Doesn't work:
jQuery("input[value='1']").attr('checked', true);
Doesn't work:
jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
Doesn't work:
Do you have another idea? What am I missing?
To find the selected radio button, you follow these steps: Select all radio buttons by using a DOM method such as querySelectorAll() method. Get the checked property of the radio button. If the checked property is true , the radio button is checked; otherwise, it is unchecked.
click(function() { var checked = $(this). attr('checked', true); if(checked){ $(this). attr('checked', false); } else{ $(this). attr('checked', true); } });
Try the code below. radio = $('input:radio[name=priority]'). val(); EDIT: Okay, this should do it for radio button validation.
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
Tip: You may also want to call click()
or change()
on the radio button afterwards. See comments for more info.
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