Checking a radio button in JQuery
I need to programmatically check a radio button given its value. The form has an id
and the input type obviously has a name (but no id). Th开发者_运维技巧e only code I managed to get working so far is:
$('input[name=my_name]:eq(1)').attr('checked', 'checked');
But I'd like to be able to check it by explicitly providing the value.
So you want to select the radio which has a particular value:
$('input[name=my_name][value=123]').attr('checked', true); // or 'checked'
Below code worked with me, if I am assigning an ID to the radio button:
<input type="radio" id="rd_male" name="gender" value="Male" />
<input type="radio" id="rd_female" name="gender" value="Female" />
$('#rd_male').prop('checked', true);
You should use prop instead of using attr . It's more recommended
$('input[name=my_name][value=123]').prop("checked",true)
In order to select the radio button programmatically, you can call a jQuery trigger or
$(".radioparentclass [value=radiovalue]")[0].click();
$('input[name=field]:eq(1)').click();
Note : field = radio button name property
Recommend use .click()
The other solution that only change radio option property or attribute
will NOT trigger radio event, you have to manually call radio event.
$("#your_radio_option_ID_here").click()
精彩评论