Rosher Consulting

Software Consulting and Development Services

jQuery : working with SELECT lists

I’ve recently had to do some work with SELECT lists using jQuery and found the documentation to be a little sparse, there’s a few good articles out there, such as this one, but I couldn’t find any that had everything I needed so I thought I would share my experiences and provide a few examples to help others, so here goes.

(Disclaimer: I’m not suggesting that any of these snippets are necessarily the best or the fastest way to do things but they get the job done, your mileage may vary!)

To handle changes and get the currently selected value:

$("#mySelect").change(function (event) {
    alert($(this).val());
}

Retrieving the text of the currently selected option:

$("#mySelect option:selected").text();

With the above you could also remove the option and just do:

$("#mySelect :selected").text();

however I’ve always thought that jQuery selectors should be as specific as possible for performance reasons, hence why I use the former, though I doubt in this case that it would make any difference.

Finding an option by its value:

var listitem = $("#mySelect option[value=" + valueToFind + "]");

Finding an option by its text value:

// The following should work but doesn't in all browsers:
var listitem = $("select option[text='" + textToFind + "']");
 
// Since the above doesn't work in all browsers we can manually search 
// through all list items on the page
var listitem = null;
$("select option").each(function() {
    if ($(this).text() === textToFind) {
        listitem = $(this);
    }
});

Retrieving all options:

var options = $("#mySelect option");

Removing all options:

$("#mySelect option").remove();

Removing the currently selected option:

$("#mySelect option:selected").remove();

Adding an option:

$("#mySelect").append("<option value=\"" + myValue + "\">" + myText + "</option>");

How many options are there:

var count = $("#mySelect option").length;

Hiding all selects on the page:

var selects = $("select:visible");
selects.hide();

You may wonder why I assigned a variable before hiding the selects, well you’ll also notice that I only selected visible elements because if you’re hiding them to show an overlay (which you would need to do in IE6) then you’ll only want to show the selects that were visible before you showed your overlay, hence why they’re stored in a variable.

That should cover most of what you’ll need to do with SELECTS, if you spot any mistakes or anything that could be improved then let me know in the comments.