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.
//Get the currently selected option's value
$(this).val();
//Get the currently selected option's title
$(this).text();
//Set the currently selected option to the supplied value
$(this).val("value");
//Get an option with a specified value
$('option[value="value-to-search-for"]', this);
//Reset select list to first value
$(this).val(""); //this doesn't work in IE
//Reset the select list to the first value
$(this).val($("option:first", this).val());
//Reset select list to blank option
$(this).val(null);
//Add an option onto the top of a select list
$(this).prepend('<option value="Option Value">Option Name</option>');
//Add an option onto the end of a select list
$(this).append('<option value="Option Value">Option Name</option>');
//Add an option before a certain option in a select list
$('option[value="value-to-search-for"]', this).before(
'<option value="Option Value">Option Name</option>',
);
//Add an option after a certain option in a select list
$('option[value="value-to-search-for"]', this).after(
'<option value="Option Value">Option Name</option>',
);
//Remove an option from a select list by value
$('option[value="value-to-search-for"]', this).remove();