5
<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!

slandau
  • 23,528
  • 42
  • 122
  • 184
  • 2
    what exactly are you trying to do? which one do you want to select? why do they have the same id? things should NEVER have the same id! – Patricia Apr 26 '11 at 14:44
  • I think they have the same idea because of the HTML Helper extension method, but I want to check the one that has the "true" value – slandau Apr 26 '11 at 14:46

5 Answers5

10
$('input[name=AmortizationTermInYears]:nth(0)').prop("checked","checked");
Khodor
  • 996
  • 1
  • 6
  • 13
  • 1
    Calling this code 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. – Serj Sagan Dec 27 '13 at 19:51
  • Using attr instead of prop might have been working by the time of posting the above answer. But this is not correct any more. Look down for the correct answer provided by Serj Sagan. – Martin Jan 09 '14 at 16:19
  • changed .attr to .prop – Khodor Jan 10 '14 at 13:02
9

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.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
3

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);
Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
2

"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" );
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
1
$('input[name=AmortizationTermInYears]');

or

$('input[name=AmortizationTermInYears]:checked');
ChrisThompson
  • 1,998
  • 12
  • 17