Check out my NEW training website for front-end web developers, FrontendMasters.com

jQuery Tip - Getting Select List Values

July 22, 2008

A friend asked me a simple question today, but it is worth noting because I have asked the same before, “How do you get the current value from a select list?”

To get the current value is very simple using val() .

$(#selectList).val();

But sometimes you may need to get the selected option’s text. This is not as straight forward. First, we get the selected option with :selected selector. Then once we have the option, we can get the text with the function, text().

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

View Demo:

Note on July 23 @9:14AM: HoyaSaxa93 wrote in to ask how to get values from select multiples. I will create the demo and code below. This would be how to set a select multiple to an array called,“foo”.

var foo = []; 
$(#multiple :selected).each(function(i, selected){
foo[i] = $(selected).text();
});

Like this article? You'll like my NEW training website for front-end web developers!

Video workshops on jQuery, JavaScript, HTML5, web performance and more.
Upgrade your front-end developer skills!

157 comments

#1. Mike Branski on July 22, 2008

This is a commonly asked question on jQuery Help, too, and very useful to know.

#2. Marc Grabanski on July 22, 2008

I’ve had to do this plenty of times, yet each time I found myself googling it. That is how I know it is time to take a moment and document it on my website to potentially help others.

#3. HoyaSaxa93 on July 23, 2008

Would this also work for select lists / listboxes that are multi-select? Would it return a delimited list or an array?

#4. rd on July 23, 2008

If you use text() on multiple elements it will return one concatenated string such as “OneTwoThree”

If you want a real array, I’d use this:

$.map($(#foo :selected), function(e) { return $(e).text(); })

There you’ll have [“One”, “Two”, “Three”]

#5. Marc Grabanski on July 23, 2008

HoyaSaxa93: val() will work just fine to get an array of values, but to get an array of text is a little different. I added code to the bottom of the article that describes how to get the selected options text to an array.

rd: I don’t understand $.map enough to comment on it, I will have to look into that!

#6. WebAPI.org on July 30, 2008

The problem is when you try to select a specific option from the list:

<select id="s1"> 
<option value="">1</option>
<option value="1">2</option>
<option value="4">3</option>
<option value="5">4</option>
</select>
<script>
$("#s1").val("4");
</script>

It doesn’t work but

$("#s1").val("1");

works just fine. Strange behaviour.

#7. Marc Grabanski on July 30, 2008

WebAPI: The results of my testing show $("#s1").val("4"); works to select the fourth option. $("#s1").val("1"); or $("#s1").val("2"); will select the second option because you don’t have a value set for the first option. To select the first option use, $("#s1").val("0");.

#8. WebAPI.org on July 30, 2008

Sometimes it selects it by value, sometimes by text, or by selectedIndex. My point is that is not consistent. I expect to always select the option based on its ‘value’ attribute, when value is provided with val(). Otherwise is just confusing and not usable.

#9. Marc Grabanski on July 30, 2008

An alternate way to do what you are asking would be: $('#s1')[0].selectedIndex = 0;. I personally have not used val to set the value of a select list before. I just tested it above based on your comment.

#10. Duranguenze on August 18, 2008

How i delete one option in the select using jquery, do you know i not have idea.

#11. Marc Grabanski on August 18, 2008

Use this code, replacing the id and value accordingly… $("#selectList option[@value=2]").remove();
This would grab select list with id, “selectList” and find an option within it that has value, “2” – then remove it.

#12. full oyun indir on August 19, 2008

thanx for information

#13. Justin S on September 12, 2008

I tried the :selected selector in my jquery but, to no avail, it keeps returning the first option’s text. I am using this on a dynamic list using a JS functoin. Any tips?

#14. Dan on September 29, 2008

Thank god for that article, would’ve had some really odd articles otherwise!

#15. Ben on October 14, 2008

Thanks for the article. My main problem is I’m trying to perform an action when a particular item is selected. For instance, if the text of the selected item == “First Option” then expose hidden div. I can’t seem to get this code into a workable format to perform actions. Please help

#16. Marc Grabanski on October 15, 2008

Ben: use a switch statement like so:

switch ($(#selectList :selected).text()) {
case First Option:
//do something
break;
case Something Else:
// do something else
break;
}
#17. Taylor on October 21, 2008

Hi All,

I’m trying to manually change the value of a select menu to a certain
option by referencing it’s value.

I’ve got the three instances I’ve tried (below) which aren’t changing
the select menu option correctly, in which am having trouble getting
the correct syntax as to how to SET the value on an “onClick” event.

<a href="#" onClick="$("#select_9").attr(value,23)); return
false;">one</a>
<a href="#" onClick="$("select[id=select_9]").attr(value,23)); return false;">two</a>
<a href="#" onClick="$("select_9").val("23"); return false;">three</a>

Can someone help me find the correct syntax?

Thanks!

#18. Alex King on November 14, 2008

Thanks for the post, very handy.

#19. software_ghost on November 22, 2008

pretty blog and useful tips .. keep posting and we will keep reading :)

#20. Barry on December 02, 2008

Thanks for the post : love the different examples used.

#21. Paul Hutson on December 16, 2008

Hello,

I’ve been trying to get information out of a select list:

var TimezoneT = $(#TimezoneP1).val();

But it doesn’t seem to retrieve it – any ideas what I’m doing wrong?

The select list looks like :

<select id="tz1" id="TimezoneP1" name="TimezoneP1">
<option value="la">la</option>
</select>

Any help would be greatly received!

Regards,
Paul

#22. Paul Hutson on December 16, 2008

It appears I may’ve been a bit of a muppet..
.. I’ve spotted my mistake, that being that I was looking for the name of the object, rather than the id, like I should’ve done.

So, in fact my code should have been :

var TimezoneT = $(‘#tz1’).val();

#23. Terry Evans on January 24, 2009

I am a jquery noob, and wondering if/how the following could be done with your tip:

I want to construct a URL with two segments using two select menus, each contributing to one of the segments, respectively. For example: mydomain.com/segment_1_option/segment_2_option/ would be created, and then the user would be sent to that url once they submit the form.

#24. Barrett on January 29, 2009

Very useful. Thank you.

#25. German Kalinec on February 03, 2009

Instead of

var foo = [];
$(#multiple :selected).each(function(i, selected){
foo[i] = $(selected).text();
});

you can use map (more elegant, I think):

var foo = $(#multiple :selected).map(function(){return $(this).val();}).get();
#26. anonymous on February 05, 2009

Hello! How to get the first options value?
How to set an attribute “selected” based on the value of the option?
Thanks in advance.

#27. Marc Grabanski on February 05, 2009

$("#mySelect option:first").val() should work to get the value of the first option.

$("#mySelect option[value=CHECKVALUE]").attr("selected",true); will work to select an option based on it’s value (replace CHECKVALUE with the value you are checking for, of course).

#28. anonymous on February 05, 2009

guess it will like this:
$("#selectId option:eq(0)").val(); (and how to change value? like this: $("#selectId option:eq(0)").val("setSomeValue");
$("#selectId option[value=‘2’]“).attr(”selected", “selected”);@
is it correct?
Thank you

#29. Marc Grabanski on February 05, 2009

1) :first and :eq(0) are the same selector. You are correct on how to change the value.

2) Never use the “@” symbol for getting an attribute, that has been depreciated and will throw errors in jQuery 1.3. Instead, your desired statement would be written as $("#selectId option[value=2]").attr("selected",true);

#30. venkat on February 11, 2009

how do we select all the option values from a select box? any idea?

#31. Craig on February 13, 2009

Be careful when using $(‘#selectList :selected’).text() because if you have a long list of options like around 3000 (extreme but it does happen) there is a noticeable delay when using the :selected selector. Jquery loops through all options to find the selected option. The best way to handle this is to go back to old school methods and use:

var ix = $( “#selectList” ).attr( “selectedIndex” );
var text = $( “#selectList”).find( “option:eq(” + ix +")" ).text();

#32. Craig on February 13, 2009

Came up with this way of doing it —

var v = $( “#selectList” ).val();
var text = $( “#selectList[value=’” + v + “’]”).text();

#33. Phillip Senn on March 16, 2009

BAM!

#34. Tim on March 26, 2009

If try the sample above I get the following array.

var foo = [];
foo = $.map($(‘#foo :selected’), function(e) { return $(e).text(); })
alert(foo);

item1,item2,item3

Instead I am looking for the following array.
‘item1’,‘item2’,‘item3’

Am I missing something here?

#35. jQuery on April 10, 2009

I was looking for selecting input field on user focus but came across this article through search engine. If anyone is looking for the same behavior read on this article:

http://jquery-howto.blogspot.com/2009/04/select-text-in-input-box-on-user-select.html

@Craig, even shorter would be:

var text = $( “#selectList[value=’” + $( “#selectList” ).val() + “’]”).text();

#36. Mahboob ISLAM on April 17, 2009
Good Job…
#37. richard on May 13, 2009

Just wanted to stop by and say thanks. One or two of the ideas on here helped me finish off a WP plugin.

#38. Aamir Afridi on May 15, 2009

very very useful and i need to read this every time i forget :)

#39. Your name on May 20, 2009

If you’re after an API for common form field tasks, this plugin provides extra methods:

http://code.google.com/p/jquery-form-extensions/

It has methods such as (plus many more):
- isRadioBox
- isChecked
- isSelected
- selectedValue
- selectedValues()

e.g. $(“#myradio”).selectedValue() would find the selected value from all the radio options.

#40. nitin on May 21, 2009

I want to sort data based on value in select Tag.

#41. fv on June 04, 2009

This is the example for :selected from JQuery website (the working one :P)
The Question is: how can i do the same but only for 1 select control? i’ve tried with:

$("#myselect").change(function () {
var str = "";
$("#myselect option:selected")


but nothing happens…
any ideas?
(PS: im new with js & jquery, so be nice pls :) )


<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
window.onload = (function(){try{

$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.trigger(‘change’);

}catch(e){}});</script>
<style>
div { color:red; }
</style>
<style>html,body{border:0; margin:0; padding:0;}</style></head>
<body>
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option selected="selected">Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
<div></div>
</body>
</html>
#42. Tod Birdsall on July 29, 2009

Thank you for the very helpful post.

#43. Kristoffer Bohmann on August 16, 2009

@FV:
> how can i do the same but only for 1 select control?

Try putting your methods inside the Document Ready method, like this:

$(document).ready(function(){ $("#myselect").change(function () { ... }); });

#44. okey on September 12, 2009

Hey thanks alot, helped me alot on my project!

#45. slade73 on October 02, 2009

Thanks for posting this. :)

#46. Eric on October 12, 2009

Ok, let’s say I get the values of multiple select box:

> ids = $(‘#ericsselectbox’).val();
> ids;
“3,5,10”

I can’t pass this back. It won’t work.
> $(‘#ericsselectbox’).val(“3,5,10”)

This selects nothing.

If I do this:
> ids_iterator = id_str.split(‘,’); // this results: “3,5,10”
> for (id in ids_iterator) $(“#ericsselectbox”).val(ids_iterator[id]);

The option whose value is 10 is select but the other two options are not! :(

Anybody know how to accomplish this?

Thanks
Eric

#47. Andy Morrow on October 21, 2009

Very useful. Thanks.

#48. keisimone on October 22, 2009

Hey your code for getting the text is wrong. it should be

$(‘#selectList option:selected’).text()

#49. aioon on October 23, 2009

thank you very much! it helps me! :)

#50. Catalin on October 23, 2009

Thank you for this simple solution. I search a lot to find this kind of simple solving my problem. Thanks !

#51. John Hamelink on November 21, 2009

Thank you so much, a very simple solution to a very small yet very irritating problem.

Thanks again,
John.

#52. Chad on November 24, 2009

Thanks, exactly what I was looking for!

#53. PolarBEar on December 01, 2009

I am having the same problem as Tim where jquery $.val() returns a multi select list as:

’item1,item2,item3 ’

instead of

‘item1’, ‘item2’, ‘item3’

This causes problems in django when trying to read the options. :(

#54. Ahsan on December 05, 2009

thanks

#55. Pushpin Symbols on December 25, 2009

Thanks. I am always pounding Google looking for help with programming JQuery as I’m too lazy to buy a book, however I think it’s time I invested in a real, physical reference. Do you have a favorite JQuery book or reference you would recommned?
Thanks,
Eric

#56. Marc Grabanski on December 27, 2009

Learning jQuery 1.3
and jQuery in Action
are the only two books I know about. Also the online e-book jQuery enlightenment.

#57. Jon on January 06, 2010

Many thanks Marc – just googled and came here. Wouldn’t have guessed the :selected modifier to get the text item in a month of Sundays! ;o)

#58. Mr. Herrit on January 16, 2010

Hello, I am trying to acomplish the same as #17. Taylor, I want to manually change wich item is selected….
For instance I have :

<div id="container">
<div id="lava">
<ul>
<li class="selected"><a href="om.html" target="hovediframe">Om Walking Artwork</a></li>
<li><a href="om-nicolas-alstrup.html" target="hovediframe">Om kunstneren</a></li>
<li><a href="kontakt.html" target="hovediframe">Kontakt</a></li>
<li><a href="betingelser.html" target="hovediframe">Vilkår og betingelser</a></li>
</ul>
</div>
</div>

How can I with javascript change wich one is selected….. In the js-code, there is something I maybe could use:

//reset the selected item
$(#lava li).removeClass(selected);

//select the current item
$(this).addClass(selected);

But instead of “this”, what should I use???? Can I give certain values to the list, and how would I do this?

Any help is much apreciated!!! Please reply in mail, if you can: n_alstrup ADD hotmail.com

#59. dima on January 18, 2010

nobody saw on jquery tiptext?

#60. Schufa on February 06, 2010

I am not so familiar with jQuery Tip but your post helped me understand more (comments are also great!)

#61. Mohamed Yusuff on February 11, 2010

Hi,
I have a scenario like a set of List boxes in a page which retrieves their values from the database. In that each List Items depends on the Previous Selections. for example : Country→State→City. So, to know the State, First we need to select the Country and that value need to be passed on to the next List Item and vice versa.

I’m using PHP and MySQL, tried some code using Javascript, but it doesn’t works. can anyone please guide me in this ?…

Thanks in advance.

#62. Dan Wasson on February 20, 2010

Thanks!

#63. Jonny on February 22, 2010

uys, I also found this better explained at http:/

#64. Mark on February 28, 2010

I am trying to create a js form, where I can have a item with a list in this case quantity and have js enter a value into a text box when I select a option.
For example when I select a quantity of 3 I would see the value 447 in the text box to the right. If possible with a symbol like £ or € in front of the value.

I have been trying something like this but I am getting more and more confused.
Any help would be greatly appreciated.


<script type="text/javascript">
function put(){
txt=document.forms0.quantity-s-c-uk.selectedValue[document.forms0.quantity-sky-c-uk.selectedValue].text
document.forms0.label-quantity-s-c-uk.value=txt
}
</script>

<select name="quantity-s-c-uk" id="quantity-s-c-uk" size="1" onBlur="put()">
<option selected="selected">0</option>
<option value="0">0</option>
<option value="149">1</option>
<option value="298">2</option>
<option value="447">3</option>
<option value="596">4</option>
<option value="745">5</option>
<option value="894">6</option>
<option value="1043">7</option>
<option value="1192">8</option>
<option value="1341">9</option>
<option value="1490">10</option>
</select>
<input name="label-quantity-s-c-uk" id="label-quantity-s-c-uk" type="text" maxlength="2" readonly="true" value="" >
#65. Wes Carmichael on March 16, 2010
$(document).ready(function(){
switch ($(#provider : selected).val()) {
case video:
$(tr#yt).css({"display":"none"});
$(tr#vid).css({"display":"table-row"});
break;
case youtube :
$(tr#yt).css({"display":"table-row"});
$(tr#vid).css({"display":"none"});
break;
}
});

the other parts:


<tr>
<td>Choose a format</td>
<td>
<select id="provider" name="provider">
<option value="">— Select a video type —</option>
<option value="video">Video file</option>
<option value="youtube">YouTube link</option>
</select>
</td>
</tr>
<tr id="vid" name="vid" style="display:none">
<td><label for="file">Select a file to upload</label></td>
<td><input type="file" name="file" id="file" /></td>
</tr>
<tr id="yt" name="yt" style="display:table-row">
<td><label for="link">Link</label></td>
<td><input type="text" name="link" id="link" size="40" maxlength="255"
title="Copy and paste the link from the YouTube site here"/><br/>
<span style="font-size:0.8em">Copy and paste the relevant link from YouTube here.</span></td>
</tr>

Any help would be greatly appreciated. I’m probably too tired to see where I’m going wrong. Even if you give me tips of where to look, that might help.

Thanks

Wes

#66. Glennyboy on April 08, 2010

Great post, but how could this without having to click the button to get the value/text and the corresponding figure to be shown on page in a div rather than alert?

Cheers
Glennyboy

#67. Glennyboy on April 08, 2010

seems I may have answered my own question:-


<script type="text/javascript">
$(document).ready(function(){
$("#getdropdown").change(function() {
var trial=$("#getdropdown option:selected").val();
//var trial=$("#getdropdown option:selected").text();
document.getElementById(‘someDivName’).innerHTML = trial;
alert(trial);
});
});
</script>

</head><body>
<select name="getdropdown" id="getdropdown">
<option value="1">Trial 1</option>
<option value="2">Trial 2</option>
<option value="3">Trial 3</option>
<option value="4">Trial 4</option>
<option value="5">Trial 5</option>
<option value="6">Trial 6</option>
</select>
<div id=someDivName>Nothing Selected Yet</div>

… perhaps this could be improved though?!

#68. Marc Grabanski on April 08, 2010

Yes, you can just do this: $("#someDivName").html( $("#getdropdown option:selected").val() )

#69. atasözleri on May 06, 2010

Thank you, wonderful examples.

Thanks again for all person.

#70. Nic Stransky on May 07, 2010

The examples above will work if you know the ID of the select you are trying to observe, but another example that

#71. H0MER on June 21, 2010

When using
$("#getdropdown option:selected") i get a hint in the firebug console
“unknown pseudo-class or pseudo-element ‘selected’”.
I got around that by first assigning the select element to a variable like that :
var variable= $("#element");
Then i assigned another variable like that:
var actualText = variable.find(":selected").text();

Does anybody know a drawaback using it like that?
Thanks in advance.

With kind regards
H0MER

#72. Marc Grabanski on June 21, 2010

HOMER: that will work just fine, you can also try $("#element :selected") as well. Not sure why option:selected wasn’t working for you.

#73. H0MER on June 21, 2010

Hi Marc,

thanks for the very fast reply :).
Sorry for that .. it WAS working, but i got that unlovely hint in the console – and thats what i dont like :).
The way i did it in the end, i dont get that error anymore, but i wasnt sure, if thats a “bad way” of solving that problem. Slowing down the application for example.

#74. Marc Grabanski on June 21, 2010

The way you are doing it is fine.

#75. Nic Stransky on June 23, 2010

The examples above will work if you know the ID of the select you are trying to observe, but another example that might be useful to readers observing the onChange of many different drop downs.

Lets say you had shopping cart checkout page with 3 line items. Each line item has a drop down for quantity. (not that i would ever write a cart like this but its for example only). Perhaps you want to update the line item total any time a quantity is changed.

1) Add a class to each of these drop downs. You might have other classes attached, but just to handle this functionality we will add our own called “line_item”.

<select name="lineitems[]" id="lineitem_0" class="bigbox line_item">
<option value="1" selected>1</option>
<option value="2">2</option>
</select>

<select name="lineitems[]" id="lineitem_1" class="bigbox line_item">
<option value="1" selected>1</option>
<option value="2">2</option>
</select>

2) Add a .change handler to your (document).ready section. Here I’m alerting the value of the selected option, but you’d add your own code to update your unobtrusive calculation function.

$(document).ready( function() {
$("select.line_item").change(function() {
alert($(this).children("option:selected").val());
});
});

3) Now when you change any of your select boxes with the “line_item” class an alert box will popup telling you the value of the selected option for THAT specific drop down.

4) Additionally, you might add more line_items using Javascript, in which case the .change handler would be unaware of these newly added drop downs. That is a discussion for creating an init function or using the Jquery bind handler that is for another post.

#76. Lars on June 26, 2010

Really trying to get something to work here..
Want to insert html file content into div based on selected value

jQuery(document).ready(function() {
jQuery(#order_type_id).change(function() {
// get the value of the selected option
switch (jQuery(#order_type_id option:selected).val())
{
case 1:
jQuery(#feeds).load(form_storage.html);
break;
case 2:
jQuery(#feeds).load(form_hardware.html);
break;
case 3:
jQuery(#feeds).load(form_license.html);
break;
case 4:
jQuery(#feeds).load(form_backup.html);
break;
case 5:
jQuery(#feeds).load(form_software.html);
break;
}
});
});

Any ideas what I am doing wrong?

#77. Lars on June 26, 2010

I know.. I put it behind an “if this then that” that didnt “fire”..

My bad..

#78. pawan damase on June 29, 2010

u can siimply write
$(‘#id’).value

#79. Marc Grabanski on June 29, 2010

Pawan damase, if you do $('#id').value will be undefined but you can do $("#id")[0].value

#80. Cyndee on June 29, 2010

I can see all the ways to select options, but I need a way to deselect all of them, is there a simple way to do that?

Thanks!

#81. Marc Grabanski on June 30, 2010

usually in the case of a select list you want to reset to the first option, $("#selectList option:first").attr('selected', true); works for this case

#82. rafs on July 02, 2010

thanks so much!

#83. eugene on July 11, 2010

helpful post…thanks!…

#84. Brian on July 15, 2010

Can anyone help me please, I feel like I am so close. I need to do something very similar but instead of getting the value from a select list, I need to get the value from the “A” tag selected, so I can use it later on down the page. How would you get the partial value of a selected link from links in an array? I am using an accordion but that doesn’t really have anything to do with this, this has to do with getting values from an array.

$(#accordion).accordion().bind( "accordionchange", function(event,ui) {
var $this = $(this),
myTitle = $(this).find(h3 > a.title).text(),
target = $(event.target);

/* = debug code === */
console.log(["myTitle =", myTitle, "target =", target]);
}

myTitle brings back all values in the array when I really just want it to bring back one and if I create an action in this it just applies it to the last element in the array when I want to apply it to the “a:selected” if that exists. Does this make sense?

Any help would be appreciated. :)

#85. Brian on July 20, 2010

Just as an FYI, I did figure it out and it had everything to do with the accordion. So here is the code that I was able to figure out how to get the results with. I actually didn’t use the A tag but if a user clicks on an accordion it will swap out the content with a hidden div. So what I needed was in “ui.whatever”. Here:

var hd = $(#hidden-div);
$(hd).hide();
$(#accordion).accordion().bind( "accordionchangestart", function(event,ui) {
var content = $(ui.content).find("#oldContent").empty();
var myDiv = $(ui.content).find(".container");
// -- THE SWAP -
$(hd).appendTo(myDiv);
$(hd).show();
});
#86. prashant kumar kushwaha on July 28, 2010

Thanks a lot, very helpful.

#87. Just and yet another variation on July 29, 2010
//If you already have the SELECT element in javascript or jQuery objects:
//$selector is a jQuery object
$selector=$("use your appropriate selector such as #selectId");
selectedItemText=$selector.children(":selected").text();

//selector is a javascript object (e.g., retrieved through getElementById()
selector=document.getElementById("use your Id such as #selectId");
selectedItemText=$(selector).children(":selected").text();
#88. Raoul on July 30, 2010

Problem returning all selected values from multiple selectboxes, where in every selectbox it is possible to select multiple items: only the selected items of the first selectbox are returned.
Anyone knows a solution?

When I have more than 1 selectbox with the id starting for example with ‘location-’

HTML:

<select  id="location-1" name="name-1" multiple="multiple">
<option value="option1">option 1</option>")
<option value="option2">option 2</option>")
</select>
<select id="location-2" name="name-2" multiple="multiple">
<option value="option3">option 3</option>")
<option value="option4">option 4</option>")
</select>

Javascript:

alert ( $(‘select[id^=location]’).val() );
#89. Marc Grabanski on July 30, 2010

Raoul,

$('select[id^=location]') returns a collection. You have to loop through them in order to get all of the values out or use the map function to turn it into an array.

var values = $(select[id^=location]).map(function(){
return $(this).val();
}).get();
#90. Agustin on August 01, 2010

Hi there! I’m trying to add a div when a X number is selected. I’ve tried to use this:

switch ($(#rooms :selected).text()) {
case 1:
//do something
break;
case 2:
//do something
break;
}
<div>
<select name="rooms" id="rooms">
<option value="1" label="room 1" selected="selected">1 room</option>
<option value="2" label="room 2">2 rooms</option>
<option value="3" label="room 3">3 rooms</option>
</select>
</div>
<div>
<label class="rooms">Room 1</label>
<select name="adults" id="adults">
<option value="1" label="1" selected="selected">1</option>
<option value="2" label="2">2</option>
</select>
<select name="kids" id="kids">
<option value="1" label="1" selected="selected">0</option>
<option value="2" label="2">1</option>
</select>
</div>

But can’t get it work. Also I need to change the label name, for room 1, room 2, and so on.
This is an example of what I’m trying to do: www.cheaprooms.com and select more than 1 room.

Thanks in advance!

#91. Marc Grabanski on August 02, 2010

Agustin, if you are going to do the switch statement based on its numeric value, then you’ll have to use $('#rooms :selected').val().

#92. Vincent on August 04, 2010

Since I found your post looking for a way to remove all the selected options in a listbox and it’s not really wrote here, here’s how we do it :

$('#provider-list :selected').remove();

This will remove all selected items form the list.

#93. Andy on August 06, 2010

This is exactly what I was looking for! Thank you!

#94. Raechel on August 09, 2010

You guys rock. Thanks for the great code samples. Much appreciated.

#95. Michael on August 09, 2010

Thanks! This was just what I was looking for.

#96. Santosh Chakrapani on August 24, 2010

To set an array to the elements of a multi-select

ids = $(‘#ericsselectbox’).val();
> ids; “3,5,10”
for (i=0;i<ids.length;i++) $(“#ericsselectbox option[value=” + ids[i] +"]“).attr(”selected", true);

#97. phpsol on August 25, 2010

Very helpfull post I really appreciate it

Thanks again

#98. Daniel on August 26, 2010

quickly found what is was looking for! Thnx!

#99. pratibha on August 27, 2010

how do i get the value and text of an option on a given index from a dropdown. Lets say i have a dropdown consisting of 5 items… and i want to pick the value/text of the 3rd one.., wat wud b the code ?

#100. raju on August 27, 2010

How do I show zip code text feild only when country “US” is selected from drop down using jquery.

#101. ismohamm on September 01, 2010

How to change the color of selected option in a select box? By defauld dark blue is displayed,but i want to change the color? could you help me out, i have googled a lot but of no use

#102. Raghavendra on September 15, 2010

I have c# list of string. I am trying to write a jquery which will get me the selected items if a listbox into this list of string.can any one help me???

#103. Mircea on September 22, 2010

Hi Marc,

I have 2 select boxes, the second one loads elements using the 1st select value. I use (1) to load the data already selected by user from database, and (2) for onchange of 1st select box.
(1) $(document).ready(function() {
str=$(‘#country_id :selected’).val();
//alert (str);
$(“#state”).load(“actions/get_counties.php?counties_id=<?=$counties_id?>&country_id=”,str).fadeIn(“slow”);

});
(2) $(document).change(function() {
str=$(‘#country_id :selected’).val();
$(‘#counties_id :selected’).remove();
//alert (str);
$(“#state”).load(“actions/get_counties.php?country_id=”+str).fadeIn(“slow”);

});
It seems i can’t select another entry from the second select box, it keeps returning the first option.
Any hint?

Thanks

#104. André Neves on September 22, 2010

Exactly what i need. Thanks.

#105. Brent on September 23, 2010

I don’t see a form element in this page, is it valid XHTML to have selects without a form ?? I’m trying your example on my site, but with a form element and I think it takes over the functionality of the go button, so it’s not working correctly.

#106. new fish on September 24, 2010

hi marc, thanks for the post.
but I would like to ask a question. I need something like selectlistitem things on my codes, but I have three properties.
I get these properties from database query.
if I would like to
return query.ToSelectListItems()

and on the JScript I get the first two properties by
$(‘#Variable’).change(function() {
$(‘Property1’).val($(‘#Variable option:selected’).val());
$(‘Property2’).val($(‘#Variable option:selected’).text());
});

how do I get the third properties ?

or do I have to use another method beside ToSelectListItems() ?

#107. ching on September 25, 2010

Hi marc,

please help me with this…

<select name="cid" class="style7" onChange="javascript:document.info.submit()" >
<option value="search" ></option>
<? while ($r=mssql_fetch_array($query)) { ?>
<option value="<?=$r[studentid]; ?>">
<? echo $r[firstname].$r[lastname].,.$r[middlename]; ?>
</option>
<? } ?>
</select>

i wanted to get the value selected (studentid), and echo it on the action page (info) on submit, triggered by the onchange event.

#108. Ricky on October 08, 2010

Hi Marc,
Is it possible to get value from coding below:



How to get “Price6000” when i click “Car 2” ?


Thx & GBU

#109. Hafsal on October 12, 2010

thanks for the post… very useful…

#110. James Radford on October 12, 2010

thanks for the post, this helps me out!

#111. Mahi on October 13, 2010

Thank u to all who have given the solution for my problem…

#112. Metaplane on October 28, 2010

Why doesn’t this work and how do I fix it?

function loadContent(elementSelector, sourceUrl) {
$(""elementSelector"").load("http://www.yoursite.com/"sourceUrl"");
}
<form method="get" action="javascript:loadContent(‘#content’,‘test_this.php?number=<?php $number; ?>’);" enctype="multipart/form-data">
<select name="number" onchange="this.form.submit()">
<option>Pick one:</option>
<option value="20" >20</option>
<option value="30" >30</option>
<option value="40" >40</option>
</select>
</form>
</div>
<div id="content">The number is not set as of yet</div>
#113. Sam on November 03, 2010

@Metaplane because you cannot put js inot the form action it must instead go into the submit property of the form tag.

#114. ngocnhut on November 08, 2010

how can I get 2 values(of table) from 01 select ??? Help me, plzzzz

#115. girish on November 13, 2010

@#98. Santosh Chakrapani

thanks for the solution

#116. Faisal on November 16, 2010

Hi, Great Work. But I have a question.
I am working on ASP.NET with Gridview control on my page. On edittemplate column i have listbox controls. I have more then three columns, but in 3 of the edittemplate columns of gridview I have provided listboxes. These listboxes contain the list of names.
My question is I would like to perform that if one name is selected from the Listbox1 and if the same name is already selected in ListBox2, it should unselect the option from the ListBox1.
BAsically comparing the two listboxes and allow to select those which are not selected. ?
Can anyone have any solution or help for this.??

#117. Beri75 on November 25, 2010

Wonderful, great tips! Thx!

#118. Jeena on November 29, 2010

Nice Info!!..

#119. Thomas on November 30, 2010

Awesome — thanks!!

#120. Brian on December 09, 2010

How do I get the value of a select option if I only have the text of the option. Any help greatly appreciated

#121. jsherk on December 16, 2010

Thanks for this article!

#122. koko on December 21, 2010

Hi Bro,
I am new to php and wordpress.
I am trying to combine the below two code.
What I want is to show job type as dropdown list and get the value when the user click submit button at the bottom the page.
Could you tell me How can I achieve this ? Thanks you.

   <div class="field">
<label for="jobtype"><?php e(‘Job type’, "wpct");?></label>
<input id="jobtype" name="jobtype" type="text" value="<?php echo cP("jobtype");?>" class="ico
title" />
</div>

<select>
<option value="parttime">Part Time</option>
<option value="fulltime">Full Time</option>
</select>

Rgds,
KoKO

#123. koko on December 21, 2010

You can see the website live through the link under my name KoKo. Thanks.

#124. Stefan on January 06, 2011

Thanks for clarifying the difference between .val() and .text().. Cheers!

#125. Robert M. on April 12, 2011

This is good information, but I’m having a difficult time finding an example of using jQuery to search through the list of select options to see if a particular text or value already exists.

#126. Robert M. on April 12, 2011

I just found the answer to my question:

var opt = $(‘option[value=“{MyValueToMatch}”]’, $(‘#MySelectElement’));
if (opt.val() == ‘’) {
alert(’{MyValueToMatch} not already in the select list’);
}

#127. Willian Lhorente on April 13, 2011

very nice article…

#128. Pedro on April 18, 2011

thank you so much for the article

#129. qingliuyu on May 04, 2011

thank you for your article!

#130. Esponjas on May 14, 2011

Great very usefull, save me your tutorial, greetens from mexico!

#131. BatsaxIV on May 17, 2011

Great !

#132. Nate on May 31, 2011

I need to read the value and the text from a listbox and then create each option value into a textbox with a dropdown next to it. So, I have a list of team members that once selected need to be assigned a role (via dropdown). How can I loop through the listbox gathering all data from the listbox using JQuery? Thanks

#133. Alexandre on June 04, 2011

Hi from Brazil… Great blog… somebody can help me with this?

i still noob in java… and i’m having some troubles with a (i think) simple function…

$(“#anuncioDestinatario”).keyup(function(){
var takeuser2 = $(‘#anuncioDestinatario’).val();
$(“#changeDest option[value=takeuser2]”).attr(“selected”,true);
});

is that simple… every time there is a “keyup” on a input, he set his value in “takeuser2”, later, he check the SELECT #changeDest with the value “takeuser2” (if exists) to SELECTED

just like that… if i change the “takeuser2” for the #changeDest event for a word there exists on the “#changeDest select”, he works… but using the string “takeuser2” he just do nothing… :S

what can be?

sorry for the bad english… :P

thankssss \o

#134. mario on June 07, 2011

hi there… i have a few selects that are created dynamically on a form and i want to check if any of them have a value of "". How can i do this.
Thanks in advance.

#135. faxianhu on August 23, 2011

nice informative post, thanks for sharing .

#136. araba ilan? ver on November 25, 2011

thanks for the post… very useful…

#137. kushal on December 16, 2011

Hi . I am trying to get the selected options text as u have done and then storing it in jquery variable as shown below
var selectedoption =$(“select :selected”).text
I am the select list on index.php and i want that as soon a user clicks any option the corresponding option’s content gets displayed below . My custom.js file is actually not being MODIDFIED At all (as FIREBUG says ).
So can u help me with this ?

#138. kushal on December 16, 2011

I have a select list on index.php and i want that as soon i click any option from the select list the corresponding option’s content gets displayed below in index.php .
My custom.js file where i have retrieved the selected option and doen other stuff is actually NOT being MODIFIED At all (as FIREBUG says ).

Here is the link to file
index.php

#139. Mahdi on January 24, 2012

hi all.
whats my problem in this code?

var code=20;        
$("#List").children("option").each(function(x) {
if ($(this).val() == ""code"")
$(this).remove();
});
<select id=List>
<?php
$result=mysql_query("SELECT * FROM `mydb`.`list`");
while ($list=mysql_fetch_array($result , MYSQL_ASSOC))
echo "<option value=\‘".$list[’code’]."\‘>".$list[’name’]."</option>";
?>

</select>
#140. vipul chauhan on February 02, 2012

Thank you for the very helpful post.

#141. Chris on February 04, 2012

Thanks for this! I bookmarked it so I can return when I forget, which I’m sure I will.

#142. james on February 22, 2012

in selecting the value like

<select id="selectthis">
<option value=first>first word</option>
</select>

$(“#selectthis”).val();

the result for this is ‘first’


for selecting the text in the option like

<select id="selectthis">
<option value=first>first word</option>
</select>

$(“select#selectthis”).val();

the result for this is ‘first word’.

#143. Ravikant Patel on March 13, 2012

Hi,
I have the following code in JSP,

<select  class="styledselect_form_1" id="consignor" name="consignor">
<option value="">—Select Consignor—</option>
<%
ArrayList consignorList = (ArrayList) session.getAttribute("consignors");
for(int i=0;i<consignorList.size();i++){
Consignors ct = (Consignors)consignorList.get(i);
>
<option value="<=ct.getConsignorID()%
>"><%=ct.getConsignorName()%></option>
<%
}
>
</select>
<select class="styledselect_form_1" id="City" name="City">
<option value="">—Select City—</option>
<
ArrayList cityList = (ArrayList) session.getAttribute("cityDet");
for(int i=0;i<cityList.size();i++){
CityList ct = (CityList )cityList.get(i);
>
<option value="<=ct.getCityID()%
>"><%=ct.getCityName()%></option>
<%
}
%>

</select>

Now I want to know that how can i choose particular item in second list say “city” on selecting an item of the first list.
plz help me
Thanks in advance….

#144. Roc on April 03, 2012

you rocks :)

#145. STB on June 01, 2012

THANK you! Cleared my question right up!

#146. Druthi on June 12, 2012

Hi All,

I am new to Jquery. I have some Issues. Your reply is appreciable. I have a form in my website. And have an option of adding clicking on “Add Another” otion to generate one more form i.e., replica of the form. So like this multiple copy of the same form can be created. Clone method is used for this. But in each form I have a drop down box onchanging of that form fields should get changed. So I have binded an onchanage event for select box class and by recognizing parent ids corresponding form fields will get chnaged onchange of drop down value. But problem is that when I click on submit validation is done in php codeignitor when the page submitted if it displays some error messages for some mandatory fields all the form fileds will get displayed doesnot matter of what is getting selected in drop down box. Sorry for this lengthier text. Hope you understand this

#147. Ashish on August 14, 2012

hi, I want all values from list box in comma seprated like an want to display it in the text box can any one please help me with that please

#148. Pozycjonowanie on August 21, 2012

Hi,
i have two array (name input)
arr1[]=1;
arr1[]=2
….

arr2[]=1
arr2[]=2
….
I can’t display values in jquery (one function )

#149. Bada on October 18, 2012

Please, how is possible if i want to select all values from the select option as a variable(list) to use somewhere else

#150. arch on November 20, 2012

m a beginner, wanted to know, how do we save a selected list item in session..

#151. Putri on December 06, 2012

Friend this work, I am happy with your tutorial. I was tried it with jsfiddle and work good. Thank you.

#152. upen on January 29, 2013

it helps me, thank u

#153. leo on February 04, 2013

i need a favour ." how to make multi-selector as selected while loading the page based on db values using jquery "

#154. larry petterson on February 27, 2013

y el ejemplo con jsf? por alli vi que habia que hacer : jQuery(‘#miForm\\:correo’).attr(“value”);

#155. Roshni Thacker on April 17, 2013

i Am creating a dynamic picklist . How to refresh the picklist after closing it . When i again open the same list i dun want the last values to retain. The problem that i am facing is its retaining the old values, and appending the new ones to it

#156. Roshni Thacker on April 17, 2013

i Am creating a dynamic picklist . How to refresh the picklist after closing it . When i again open the same list i dun want the last values to retain. The problem that i am facing is its retaining the old values, and appending the new ones to it

#157. Jonas on May 07, 2013

Splendid! Worked as a charm! Thanks alot!

Leave a comment

Comment in textile images by gravatar