How to Set the Selected Index of a Dropdown using jQuery CodeUnit 20 JUN 2011

There are a number of ways to set the selected index of a dropdown list when it comes to jQuery, though unfortunately one of them only works about half the time, basically whenever the guys behind the library remember to fix a particular bug in the system for that particular release.

However, these two methods below all work flawlessly, and should give you all the tools you need (note the first two examples are actually the same method):

// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0'); 

// sets selected index of a select box to the option with the value ""
$("select#elem").val(''); 

// sets selected index to first item using the DOM
$("select#elem").get(0).selectedIndex = 0;

The method you would expect to see but which I have omitted because it is a recurring bug that gets fixed in most but not all releases is of course the manipulation of the selectedIndex attribute through the attr() call. But seeing as the DOM method works well, there is no reason to even bother listing this one anymore!

Nifty.

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.