jQuery Tip - Getting Select List Values: jQuery, Tutorial

jQuery Tip - Getting Select List Values

Category: JavaScript & jQuery Tags: jQuery, Tutorial | Written on Jul 22, 2008

Chris Hartjes 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().

JavaScript:
  1. $('#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().

JavaScript:
  1. $('#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".

JavaScript:
  1. var foo = [];
  2. $('#multiple :selected').each(function(i, selected){
  3.     foo[i] = $(selected).text();
  4. });

Comments

#1. Mike Branski http://www.leftrightdesigns.com/ on Jul 22, 2008
This is a commonly asked question on jQuery Help, too, and very useful to know.
#2. Marc Grabanski http://marcgrabanski.com on Jul 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 Jul 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 Jul 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 http://marcgrabanski.com on Jul 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 http://WebAPI.org on Jul 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 http://marcgrabanski.com on Jul 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 http://WebAPI.org on Jul 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 http://marcgrabanski.com on Jul 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 Aug 18, 2008
How i delete one option in the select using jquery, do you know i not have idea.
#11. Marc Grabanski http://marcgrabanski.com on Aug 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 http://fulloyunin.com on Aug 19, 2008
thanx for information
#13. Justin S http://www.justinslamka.com on Sep 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 http://www.thoughtden.co.uk on Sep 29, 2008
Thank god for that article, would've had some really odd articles otherwise!
#15. Ben on Oct 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 http://marcgrabanski.com on Oct 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 Oct 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 href="#" onClick="$("select[id='select_9']").attr('value','23')); return false; li>

a href="#" onClick="$("select_9").val("23"); return false;"

Can someone help me find the correct syntax?

Thanks!
#18. Alex King http://shortdivision.com on Nov 14, 2008
Thanks for the post, very handy.
#19. software_ghost http://blogs.helion-prime.com on Nov 22, 2008
pretty blog and useful tips .. keep posting and we will keep reading :)
#20. Barry http://calisza.wordpress.com on Dec 02, 2008
Thanks for the post : love the different examples used.
#21. Paul Hutson on Dec 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 Dec 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. dr.emi http://psdremi.co.cc on Dec 22, 2008
Hi!
I use jQuery Loader Content to auto complete the state select tag.

function loadContentKabupatenKotaDiploma(id) {
$("#contenPanKabupatenKotaDiploma").hide();
$("#contenPanKabupatenKotaDiploma").load("../dre-includes/url_pendidikan/findKabupatenKota.php?id="+id+"", '', callbackKabupatenKotaDiploma);
}
function callbackKabupatenKotaDiploma() {
$("#contenPanKabupatenKotaDiploma").show();
}
$(document).ready(loadContentKabupatenKotaDiploma(id));





then here are the html code:
<label>Propinsi</label>
<?
$query="SELECT * FROM master_propinsi";
$result=mysql_query($query);
?>
<select class="input" name="id_propinsi_pendidikan[]" onChange="loadContentKabupatenKotaDiploma(this.value)">
<option value="">Pilih Propinsi</option>
<?
while($rows = mysql_fetch_array($result))
{
?>
<option value="&lt;? echo $rows['id']; ?>"><? echo $rows['nama_propinsi']; ?></option>
<?
}
?>
</select>
<div class="spacer"> </div>
<div id="contenPanKabupatenKotaDiploma"> </div>

I create a script for external file: findKabupatenKota.php

<label>Kabupaten/Kota</label>
<select class="input" id="id_kabupaten_kota_pendidikan" name="id_kabupaten_kota_pendidikan[]">
<option>Pilih Kabupaten/Kota</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=&lt;? echo $row['id']; ?>><? echo $row['nama_kabupaten_kota']; ?></option>
<? } ?>
</select>

AND now I want to get the value of id_kabupaten_kota_pendidikan[].

I try this way for POST FORM Action:

for($d=0;$d <= count($_POST['nama_pt']);$d++)
{
$jQueryKabKPendidikan[$d] = "<script>$('[@name=id_kabupaten_kota_pendidikan]')[$d].val(); </script>";
if(!empty($_POST['nama_pt'][$d]))
{
mysql_query("INSERT INTO `data_pendidikan_terakhir` (
`id_peserta` ,
`id_jenjang` ,
`tahun_lulus` ,
`id_jurusan` ,
`nama_pt` ,
`id_propinsi` ,
`id_kabupaten_kota` ,
`tanggal_input`
)
VALUES (
'".$noUrut."',
'".clearString($_POST['id_jenjang'][$d])."',
'0000',
'".clearString($_POST['id_jurusan'][$d])."',
'".clearString($_POST['nama_pt'][$d])."',
'".clearString($_POST['id_propinsi_pendidikan'][$d])."',
'".clearString($jQueryKabKPendidikan[$d])."',
'".thisTime."')");
}

}

The result is $jQueryKabKPendidikan[$d] = 0;

Well... do you have one idea to get multiple value from a selected field ? and is combination of jQuery + PHP a better way ??? Or I must use a complete Ajax Post Action without PHP ?

#24. Terry Evans http://www.vibe9design.com/ on Jan 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.
#25. Barrett on Jan 29, 2009
Very useful. Thank you.
#26. German Kalinec on Feb 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();
#27. anonymous on Feb 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.
#28. Marc Grabanski http://marcgrabanski.com on Feb 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).
#29. anonymous on Feb 05, 2009
guess it will like this:
1.$("#selectId option:eq(0)").val(); (and how to change value? like this: $("#selectId option:eq(0)").val("setSomeValue");?)
2.$("#selectId option[@value='2']").attr("selected", "selected");
is it correct?
Thank you
#30. Marc Grabanski http://marcgrabanski.com on Feb 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);
#31. venkat on Feb 11, 2009
how do we select all the option values from a select box? any idea?
#32. Craig on Feb 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();
#33. Craig on Feb 13, 2009
Came up with this way of doing it --

var v = $( "#selectList" ).val();
var text = $( "#selectList[value='" + v + "']").text();
#34. Phillip Senn http://www.PhillipSenn.com on Mar 16, 2009
BAM!
#35. Tim on Mar 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?
#36. jQuery http://jquery-howto.blogspot.com on Apr 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();
#37. Mahboob ISLAM on Apr 17, 2009
Good Job...
#38. richard http://www.theenglishguy.co.uk/ 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.
#39. Aamir Afridi http://www.aamirafridi.com on May 15, 2009
very very useful and i need to read this every time i forget :)
#40. Your name http://www.shrinkrays.net 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.
#41. nitin on May 21, 2009
I want to sort data based on value in select Tag.
#42. fv on Jun 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>
#43. Tod Birdsall http://tod1d.net on Jul 29, 2009
Thank you for the very helpful post.
#44. Kristoffer Bohmann http://www.bohmann.dk on Aug 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 () {
...
});
});
#45. okey http://oktaka.com on Sep 12, 2009
Hey thanks alot, helped me alot on my project!
#46. slade73 http://slade73.blogspot.com on Oct 02, 2009
Thanks for posting this. :)
#47. Eric on Oct 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


#48. Andy Morrow http://domain.com on Oct 21, 2009
Very useful. Thanks.
#49. keisimone on Oct 22, 2009
Hey your code for getting the text is wrong. it should be

$('#selectList option:selected').text()
#50. aioon http://www.aioon.de on Oct 23, 2009
thank you very much! it helps me! :)
#51. Catalin http://www.my-security-software.com on Oct 23, 2009
Thank you for this simple solution. I search a lot to find this kind of simple solving my problem. Thanks !
#52. John Hamelink http://syntaxmonster.net on Nov 21, 2009
Thank you so much, a very simple solution to a very small yet very irritating problem.

Thanks again,
John.
#53. Chad http://www.mediamarketer.scom on Nov 24, 2009
Thanks, exactly what I was looking for!
#54. PolarBEar on Dec 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. :(
#55. Ahsan http://domain.com on Dec 05, 2009
thanks
#56. Pushpin Symbols http://www.mappointsymbols.com on Dec 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
#57. Marc Grabanski http://marcgrabanski.com on Dec 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.
#58. Jon on Jan 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)
#59. Mr. herretøj http://www.walkingartwork.com on Jan 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">



</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
#60. mr. herretøj http://www.walkingartwork.com on Jan 16, 2010
Regarding the post above:
Here is the code in "writing"

<div id="container">
<div id="lava">



</div>
</div>
#61. dima http://www.x0.org.ua on Jan 18, 2010
nobody saw on jquery tiptext?
#62. Vision Statement Examples http://finance.varolmak.com/2010/01/vision-st on Jan 30, 2010
I have read your entire article. Very useful information summer. Thanks
#63. Schufa http://www.kreditohne-schufa.com on Feb 06, 2010
I am not so familiar with jQuery Tip but your post helped me understand more (comments are also great!)
#64. Mohamed Yusuff http://domain.com 1 month ago
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.
#65. Dan Wasson http://domain.com 2 weeks, 5 days ago
Thanks!
#66. Jonny http://macdonjo.byethost3.com/ 2 weeks, 3 days ago
uys, I also found this better explained at http:/
#67. Mark http://domain.com 1 week, 4 days ago
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.forms[0].quantity-s-c-uk.selectedValue[document.forms[0].quantity-sky-c-uk.selectedValue].text
document.forms[0].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="" >

Leave a Comment

Other Reading - Categories