9

I have the following select box.

<select id="selId">
     <option id='1' value='1'>1</option>
     <option id='2' value='2'>2</option>
     <option id='3' value='3'>3</option>
     <option id='4' value='4'>4</option>
     <option id='5' value='5'>5</option>
</select>

In jquery I am doing the following to select the value 2 in the select box.:

...
$("select#selId").find("option#2").attr("selected", "selected");
...

The same code sets the value of 2 in the select box in IE8 and Firefox. But its not working in IE9.

I am using JQuery 1.6.1 version

Puru
  • 8,475
  • 26
  • 69
  • 89
  • Which version of jQuery are you using? v1.5.1 was the first version to [support IE9](http://blogs.msdn.com/b/ie/archive/2011/03/02/jquery-1-5-1-supports-ie9.aspx) as a top level browser. – andyb Jun 13 '11 at 11:13

4 Answers4

20

Instead of setting the selected attribute, just use .val("2").

See here: jsFiddle

Dan Beaulieu
  • 18,664
  • 18
  • 94
  • 132
DavidGouge
  • 4,453
  • 5
  • 29
  • 45
  • Please remove '' from $('document') – Haradzieniec Nov 28 '12 at 07:01
  • 3
    Nope means no? Why not? $(document).ready(function() {}); but not $('document').ready(function() {}); and your jsfiddle doesn't work because of that at least when I click on the link. Once I remove ' ', it loads fine. – Haradzieniec Nov 28 '12 at 16:32
5

Anyway, this worked well on IE9 if you want to mantain the "SELECTED" attribute

$("select#selId").find("option#2").attr("selected", true);

http://jsfiddle.net/cqENs/

VAShhh
  • 3,464
  • 2
  • 22
  • 35
  • 1
    +1 nice answer. A much nicer approach to actually maintain the attribute. I actually thought val() would do it behind the scenes but it doesn't! – andyb Jun 13 '11 at 11:57
2

You could use val() to set the option instead - see Change the selected value of a drop-down list with jQuery

Community
  • 1
  • 1
andyb
  • 42,692
  • 12
  • 119
  • 148
1

change this one

$("select#selId").find("option#2").attr("selected", "selected");

into this one

$("select#selId").find("option#2").attr("selected", true); 
Vivek
  • 10,682
  • 14
  • 46
  • 65