Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select a radio button with jquery

Tags:

html

jquery

<input type="radio" value="True" propertyname="AmortizationTermInYears" onchange="showAmortizationTermInYears();UpdateField(this);" name="AmortizationTermInYears" id="AmortizationTermInYears" amortizationterminyearsradio="true">

<input type="radio" value="False" propertyname="AmortizationTermInYears" onchange="showAmortizationTermInYears();UpdateField(this);" name="AmortizationTermInYears" id="AmortizationTermInYears" checked="checked">

How can I select one of these radio buttons using Jquery when the page loads?

Thanks!

like image 277
slandau Avatar asked Apr 26 '11 14:04

slandau


4 Answers

$('input[name=AmortizationTermInYears]:nth(0)').prop("checked","checked");
like image 61
Khodor Avatar answered Nov 02 '22 02:11

Khodor


This will do the trick:

$(document).ready(function() {
   $("input[name='AmortizationTermInYears'][value='True']").attr("checked", "checked");
});

You need to search by both name and value then set the checked attribute.

Live test case.

like image 36
Shadow Wizard Hates Omicron Avatar answered Nov 02 '22 02:11

Shadow Wizard Hates Omicron


Although the question is mostly about how to select an element, I do notice that everyone is using the attr() function and, usually, this is wrong because calling this function only works once. If you call this, then the user checks a different one, if you call this the second time, it will not work. the correct way to do it is to use prop()

$('input[name=AmortizationTermInYears]:nth(0)').prop('checked', true);
like image 40
Serj Sagan Avatar answered Nov 02 '22 02:11

Serj Sagan


"id" attribute should not be used again. You have given id="AmortizationTermInYears" to both radio buttons. It is wrong according to standards. Set different ids to both radio buttons.

Also you can select radio button by specifying id:

$('#AmortizationTermInYears').attr( "checked", "checked" );
like image 35
Somnath Muluk Avatar answered Nov 02 '22 03:11

Somnath Muluk