Tuesday 16 March 2010

Select / Dropdownlist jQuery

1. Get the value of the selected item

$("#dropdownlist").val()

2. Get the text of the selected item

You would think this would be easy as well, but it isn’t. You cannot just use the text() method on the combobox. That 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.

$("#dropdownlist option:selected").text()

3. Find out when the select value changed

$("#dropdownlist").change(function() { /* do something here */ });

4. Programmatically set the selected item.

$("#dropdownlist").val(2);

5. 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: $(“#dropdownlist”).html(“”);

Add to the list: $(“”).appendTo(“#dropdownlist”);

No comments:

Post a Comment