Simon Holywell

Text Post

jQuery Using and Manipulating Select Lists

JQuery is a fantastic tool but sometimes its functionality can be obscure or doing it one way might not work in a certain browser (MSIE6 anybody!).  I have often found myself trying to remember the best way to work with HTML select lists so I am compiling this list of hints for future use and I hope that you find it useful.  All the examples below are written where this represents the select element of the select list.

First up getting the selected value from a select list is as simple as using the jQuery shortcut $(this).val();.  Simple isn’t it!  Setting the selected item is just as easy too…

jQuery has a nice shortcut for setting the selectedIndex/value of an HTML select list and its syntax is as so $(this).val('value');.

Finding an option in a select list by its value works out to be something like this $('option[value="value-to-search-for"]', this);.

Often I need to be able to reset the select list to its initial state when clearing/resetting a form for the next submission.  There is a jQuery shortcut for this which is $(this).val('');, but it does not work in IE for whatever reason so I devised $(this).val($('option:first', this).val());.  This basically sets the select lists value equal to the first option in the list.

The next item on the list is resetting the select list to a blank option, which is easy with the following syntax $(this).val(null);.

Now to add an option into a select list with jQuery $(this).append('<option value="Option Value">Option Name</option>'); and to remove an option from the list by value $('option[value="value-to-search-for"]', this).remove();.

The aforementioned tips and some extras are included in a syntax highlighted manner below for your perusal.

http://gist.github.com/294741

View Comments
Posted on Monday, August 10, 2009. Tagged with: JavascriptjQueryComputingInternet

Comments powered by Disqus

Simon Holywell

My name is Simon Holywell and I am a Zend Certified PHP Developer with experience working for Web agencies, marketing companies and corporate IT in Australia and the United Kingdom. When I am not developing I can be found riding my motorbike, skateboarding or snowboarding. More information about my work history can be found on my online CV.

Facebook
LinkedIn
Flickr
Twitter
del.icio.us

Previous Next