H. Ferrence
H. Ferrence

Reputation: 8116

How to pre-select a radio button in jQuery

I want to pre-select the first radio button in the following set:

HTML

<input type="radio" value="0" name="serviceNoteType[1]">
<input type="radio" value="1" name="serviceNoteType[1]">

jQuery

var i = 1; // for sake of this example
$('[name="serviceNoteType\\['+ i +'\\]"]').prop('checked', true);

The result is that the second radio button gets selected and I want the first one selected. How to I target the first radio button?

Upvotes: 0

Views: 2232

Answers (3)

sareed
sareed

Reputation: 780

The names need to be different. Your selector will only check the last element rendered of that name.

$('[name="serviceNoteType\\['+ i +'\\]"]:first-child').prop('checked', true);

Untested so the syntax may be slightly off but should give you the idea.

Upvotes: -1

Riad
Riad

Reputation: 3860

More shorter form. Try this:

$("input:radio:first").attr('checked', true);

Upvotes: 1

j08691
j08691

Reputation: 207953

You can add .first() to your selector:

var i = 1; // for sake of this example
$('[name="serviceNoteType\\['+ i +'\\]"]').first().prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" value="0" name="serviceNoteType[1]">
<input type="radio" value="1" name="serviceNoteType[1]">

Upvotes: 3

Related Questions