Hassan Sardar
Hassan Sardar

Reputation: 4523

Make first Radio button checked in Loop using name attribute

I have list of Radio buttons in loop like this:

<input type="radio" name="courses" id="course_1" value="1">
<input type="radio" name="courses" id="course_2" value="2">
<input type="radio" name="courses" id="course_3" value="3">
<input type="radio" name="courses" id="course_4" value="4">   

I want to make first radio checked using name attribute not id.

Here is my Fiddle : http://jsfiddle.net/8AcYg/1/

Upvotes: 1

Views: 2621

Answers (4)

rab
rab

Reputation: 4144

You can do it with native document method getElementsByName or querySelector

document.getElementsByName('courses')[0].checked = true;

or

document.querySelector('[name=courses]:first-child').checked = true;

Upvotes: 0

sachin chavda
sachin chavda

Reputation: 86

Do this by setting first child's attribute to true

$('input:radio[name=courses]:first-child').attr('checked',true);

See in jsfiddle

Upvotes: 0

Rituraj ratan
Rituraj ratan

Reputation: 10378

$("input[name='courses']:eq(0) ").attr("checked","checked");

or

$('input[name="courses"]:eq(0)').prop('checked', true);

demo

reference attribute-equals-selector , attr , prop

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Use .first()

$('input[name="courses"]').first().prop('checked', true)

Demo: Fiddle

You can also use :first, :eq(0) or .eq(0) to do the same

Upvotes: 6

Related Questions