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:
Check it out…