JQuery and the DropDownList – ComboBox

After playing around with Combo boxes for a while within jQuery I thought it would be good to write down, mainly so I can remember how to find and play with properties from within jQuery.  So here we go, here is the HTML that we’ll be using:

 <select id=”ComboBox” >
   <option value=”1″>Value 1</option>
   <option value=”2″>Value 2</option>
   <option value=”3″>Value 3</option>
   <option value=”4″>Value 4</option>
   <optgroup label=”Group1″>
      <option value=”5″>Value 5</option>
      <option value=”6″>Value 6</option>
      <option value=”7″>Value 7</option>
      <option value=”8″>Value 8</option>

Get the value of the selected item

This is the easiest.  Use the val method.


Get the text of the selected item

If you just try using the text() method on the combobox, this will give you the text values of all of the options in a single string.  Not what you want.  The trick is to use the :selected query modifier on the option.

$(“#ComboBox option:selected”).text()

Find out when the select value changed

This is also rather easy with JQuery.

$(“#ComboBox”).change(function() { /* do something here */ });

Programmatically set the selected item.


Modify the list.

Modifying a select element is not fundamentally different than modifying any other element in the dom, but there are a few basics here to keep in mind. Mainly: try to avoid using the dom directly.  Create html strings instead.

Clear the list:   $(“#ComboBox”).html(“”);

Add to the list: $(“<option value=’9’>Value 9</option>”).appendTo(“#ComboBox”);

For more information check out the jQuery API