6 jQuery snippets you can use to manipulate select inputs
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 couldn’t be simpler. Remember how before jQuery, you had to use selectedIndex and all those lovely javascript methods. I do, and I don’t 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 jQuery’s “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’re getting the text() value of a selected option, only this time we’re going to use it inside a switch statement.
5. Removing an option.
$("#selectList option[value='2']").remove();
Using an attribute filter, we can find and therefore manipulate specific options within a select list. In this example we’re telling jQuery to find the option with value=”2″ and then remove it from the select list. We can similarly add options to a select list as we’ll see in example 6.
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'); }); });
Originally posted by Jeremy Martin, here we have 2 select lists and 2 buttons. If you click the “add” button, we remove the selected option from select1 and add that same option to select2. The “remove” button just does things the opposite way around. Thanks to jQuery’s chaining capabilities, what was once a rather tricky undertaking with JS can now be done in 6 lines of code.
And there you go. That wasn’t so bad now was it ? If you have any other handy snippets, or you’ve found an easier way to do something already covered here, why not leave a comment and share the love!
Update:
Incidentally, a few hours after first publishing this post I came across the following “select element cheat sheet”. Technically speaking, it may be a little big to be called a cheat sheet, but the author has given a very thorough and practical guide which I’m definitely going to be making use of.
Good one Barry!
Thanks Chris.
jQuery doesn’t even support xPath anymore and using the @ in attribute selectors will break in > jQuery 1.3. I would tend to think using .val() on a multiple select would be preferable to the dom navigation/iteration method. So preferable, in fact, that the other really shouldn’t be considered an alternative. Furthermore, if you want to move options between selects, you can just .appendTo() without the .remove() first.
Hi ajpiano,
Thanks for the excellent response. I admittedly haven’t spent much time going through jQuery 1.3 just yet, so the I’m ashamed to admit that the lack of xpath support comes as a bit of a surprise to me.
I’ll have a look at the code again and amend where necessary. Thanks again for taking the time to set me straight 🙂
Looks good.
On the one hand, I love seeing people benefit from my blog – that’s what it’s there fore. But on the other hand, when fellow publishers copy and paste my content, line for line, I expect credit. The code in snippet 6 is, to the character, an excerpt from my code here: http://blog.jeremymartin.name/2008/02/easy-multi-select-transfer-with-jquery.html.
I would like to give the benefit of the doubt, but you didn’t even bother to rename the button or multi select ID’s. Additionally (and ironically), as Ajpiano correctly pointed out, you even copied my unnecessary use of remove() before the appendTo().
Hi Jeremy,
Thanks for commenting, much appreciated. I’d like to apologise for any offense caused. It was not my intention to take credit away from anyone and I will be updating the post accordingly. I did indeed copy-paste from your original post and stored it in my Snippely app. That was some time ago and I unfortunately couldn’t remember where the original code came from.
Thanks again.
Well in light of your comment, no offense taken 😉
I apologize if I “came down” a little hard – I can see now how that was just an honest mistake. On a different note, keep up the good work!
Not at all, I appreciate that you took the time to comment at all. Most people just don’t even bother.
Thanks again 🙂
Great article and collection of jQuery code snippets. I also like the jQuery Howto blog… it has collection of similar posts …
Good thnx very much
thx men¡¡ 🙂
Thanks!
Can I suggest a seventh tip?
$('select#name option[value="2"]').attr('selected', 'selected');
This code will select the element where …. Of course you can replace the number “2” by a variable.
@Wizz
You’re supposed to use .val() to set the value of a select. $(“#name”).val(2); would achieve same.
Good collection of jQuery snippets mate. I have also linked to yours from my blog post below where I am trying to collect the most useful and common jQuery code snippets for JavaScript over the web. Here is the title and the link to the jQuery link compilation endeavor:
Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance
http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/
Thanks Shahriar 🙂 I’ve checked your post out, very cool.. keep it up and thanks for adding me to your list.
Thanks, tip number 5 was really handy.
There is nothing better than a short condensed straight-to-the-point info source in this information age. Excellent post.
about Moving options from list A to list B.
what if you do not want it removed from A but just copied to B. In this example it removes it from the list A and i want to keep my list A as it is.. any suggestions?
yes, excellent post, except for the whole plagiarism part. *tsk tsk*
how can we remove certain options from Select list based on the text value of that option ?
(note: it is not just the selected option , but some of the options need to be removed based on the text)
e.g. I want to remove options that have the text starting with *
*one*
two
three
*four*
thank you! this helped so much
This is great! Thanks. Now what about if you want to add a new option? Given the strings for text and value, how can you add a new one to the list dynamically?
Thank you!
i´m trying this:
$(“#mySelect option:last”).bind(“click”, function(){
myFunctionToGetCheckBoxValues();
});
but on chrome browser does not work, does anyone have solve this issue?