Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a radio button with jQuery?

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?

like image 279
Alexis Avatar asked Apr 14 '11 15:04

Alexis


People also ask

How can I tell if a radio button is checked?

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.

How do you check radio button is checked or unchecked in jQuery?

click(function() { var checked = $(this). attr('checked', true); if(checked){ $(this). attr('checked', false); } else{ $(this). attr('checked', true); } });

How check radio button is empty or not in jQuery?

Try the code below. radio = $('input:radio[name=priority]'). val(); EDIT: Okay, this should do it for radio button validation.


1 Answers

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.

like image 193
Mike Thomsen Avatar answered Sep 23 '22 18:09

Mike Thomsen