When it comes to manipulating the DOM, fewer elements are more tiresome than the good old select input. Fortunately for us, jQuery makes what was once a headache, a walk in the park. Listed below are 6 snippets which should make manipulating those selects more pleasant than say, pulling your own teeth.


1. Getting the value of a selected option.

$('#selectList').val();

This could not be simpler. Remember how before Jquery, you had to use selected Index and all those lovely JavaScript methods. I do, and I do not miss it one bit.


2. Getting the text of a selected option.

$('#selectList :selected').text();

Similar in concept to the first snippet with one difference. Where the first example gives you the value of the selected option, this example gives you the actual text contained inside the option tag.


3. Getting the text/value of multiple selected options.

var foo = []; $('#multiple :selected'). each(function(i, selected) { foo[i] = $(selected).text(); } ); // to get the selected values, just use .val() - this returns a string or array foo = $('#multiple :selected').val();

Once again, the same concept as the first two examples, except we’re now using jQuerys each() method to loop through all selected options in a multiple select list. Each value or text value is read into an array for later use.


4. Using selected options in conditional statements

switch ($('#selectList :selected').text()) { case 'First Option': //do something break; case ' Something Else': // do something else break; }

Much like example 2, we are getting the text() value of a selected option, only this time we are going to use it inside a switch statement.



Like our site? Be a member of Coolajax fan page to get daily posts updates!

recommended-tutorial You May Like This Posts!

» Show Effect in jquery

» Page redirection with Live time left preview using jquery

» TubePlayer A YouTube Player jQuery Plugins

» Improve your portfolio site with 18 jQuery scripts

» Jquery Tutorial: Part I

  tuts_view Total Read: 995
blog comments powered by Disqus

Topics

Coolajax Fans

coolajax fan page on Facebook