Jos
Jos

Reputation: 325

Set attribute selected of particular option of select box using jquery

I have a select box with following options

select id="box" ><br/>
  option value="1"Same Day<br/>
  option value="5">96<br/>
  option value="4">72<br/>
  option value="3">48<br/>
  option value="2">24<br/>
select>

I Want to add attr selected to option value '4' , i know i can show it selected via

$("#box").val(4)

But this just shows it selected but does not add attribute selected to option 4, what i want is to add attribute selected to option.

Please suggest

Thanks

Upvotes: 1

Views: 5729

Answers (1)

jAndy
jAndy

Reputation: 235962

$('#box').children('option:eq(3)').attr('selected', 'selected');

That makes usage of the eq() selector which querys the index you specify.

Slightly faster (even if it's more typing) would be the method .eq() instead of the selector:

$('#box').children('option').eq(3).attr('selected', 'selected');

Since .eq() uses array slices instead of query'ing over Sizzle. As you notice correctly, both versions start indexing at zero.

Ref.: :eq, .eq()

Upvotes: 1

Related Questions