Snippet – jQuery: 6 Snippets to manipulate Select inputs

  • Share
  • Share

Interesting set of snippets to manipulate select inputs using jQuery.

1. Get value of the selected option.
Simple one line query to get the selected option value…

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

2. Get text of the selected option.
Similar to snippet:#1, while #1 gets the value of the selected option, #2 gets the actual text provided in the option tag

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

3. Get the text/value of multiple selected options.
Similar to Snippet #1 & #2 but the difference being jQuery’s each() function is being used to loop through the selected options in the list & the result is stored in an array for later use.

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

4. Selected options in conditional statements
Similar #2, we’re getting the text() value of a selected option, only difference being we are going to use it inside a switch statement.

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

5. Remove an option
Self explanatory :)

$("#selectList option[value='2']").remove();

6. Moving options from list A to list B.

$().ready(function() {
$('#add').click(function() {
return !$('#select1 option:selected').appendTo('#select2');
});
$('#remove').click(function() {
return !$('#select2 option:selected').appendTo('#select1');
});
});

Related posts:

  1. Snippet – jQuery: Trim strings using jQuery
  2. Snippet – Prototype: Object extending
  3. Snippet – jQuery: Get content from another page
  4. Defaultvalue – Gives value to empty inputs jQuery plugin
  5. Create feature items widget similar to flash using jQuery
This entry was posted in Code Snippets, jQuery. Bookmark the permalink.

One Response to Snippet – jQuery: 6 Snippets to manipulate Select inputs

  1. admin says:

    Check it out…

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>