Jake
Jake

Reputation: 3486

marking a radio button as checked jquery

I am using the following code, why doesn't it work?

javascript:$('input[id=mod1radio]:eq(1)').attr('checked', 'checked');

and

<input id="mod1radio" type="radio" name="group1" value="24">

Upvotes: 1

Views: 294

Answers (2)

irrelephant
irrelephant

Reputation: 4111

There is only input. eq(1) would select the second one. @charlietfl suggests using prop() instead of attr() for jQuery >= version 1.6.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Since the id mod1radio has to be unique, just use

$('#mod1radio').prop('checked', true);​

JSFiddle http://jsfiddle.net/mFkQQ/3/

If mod1radio should be a class instead, then use

$('.mod1radio:eq(0)').prop('checked', true);​

Fiddle http://jsfiddle.net/mFkQQ/5/

Upvotes: 0

Colleen
Colleen

Reputation: 25549

Because eq() uses 0-based indexing (i.e. if you only have one of those, which you should since ids are distinct, you're selecting off the end of the array. eq(0) should work).

But if you have an id, why do that complicated select anyway? Why not just $("#mod1radio")?

also, as mentioned in the comments, attr() is deprecated, you should be using prop()

Upvotes: 2

Related Questions