1383

Usually I use $("#id").val() to return the value of the selected option, but this time it doesn't work. The selected tag has the id aioConceptName

html code

<label for="name">Name</label>
<input type="text" name="name" id="name" />

<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>
Andy
  • 4,783
  • 2
  • 26
  • 51
William Kinaan
  • 28,059
  • 20
  • 85
  • 118
  • 2
    could you show the markup of element `#aioConceptName` – Jorge May 18 '12 at 20:13
  • 2
    it's strange because works on this example http://jsfiddle.net/pAtVP/, are you sure that the event it fires in your enviorment? – Jorge May 18 '12 at 20:30
  • 6
    possible duplicate of [jQuery: Get selected option from dropdown](http://stackoverflow.com/questions/2380230/jquery-get-selected-option-from-dropdown) – Kenny Linsky Aug 21 '13 at 15:54
  • 13
    A late thought, but .val() won't work unless you set the `value` attribute on those ` – Jacob Valenta Oct 26 '13 at 16:38
  • 9
    Recent versions of jQuery (tested with 1.9.1) have no issues with this markup. For the above example, `$("#aioConceptName").val()` returns `choose io`. – Salman A Feb 08 '15 at 14:44
  • 2
    Doesn't it seem odd to ask a question about legit-broken code, and then to edit your question with the fix according to the correct answer, while not updating the statement that says it's broken? – HoldOffHunger Jan 16 '18 at 22:43
  • Possible duplicate of [Bootstrap-select - how to fire event on change](https://stackoverflow.com/questions/25720986/bootstrap-select-how-to-fire-event-on-change) – KyleMit Apr 18 '18 at 15:04
  • @JacobValenta If an option doesn't have a `value` attribute, it defaults to the text. – Barmar Aug 24 '18 at 16:27
  • for `.val()` you should add `value` attribute to `option` tags with jQuery method `.find(":selected")`, otherwise [following accepted answer](https://stackoverflow.com/a/10659117/5803974) will work – Satish Dec 16 '19 at 06:18

35 Answers35

2254

For dropdown options you probably want something like this:

For selected text

var conceptName = $('#aioConceptName').find(":selected").text();

For selected value

var conceptName = $('#aioConceptName').find(":selected").val();

The reason val() doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the :selected property to the selected option which is a child of the dropdown.

DragonFire
  • 3,722
  • 2
  • 38
  • 51
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • 52
    Ah, okay, you've updated your question with HTML. This answer is now irrelevant. As a matter of fact, `.val()` should work in your case-- you must have an error elsewhere. – Elliot Bonneville May 18 '12 at 20:17
  • 15
    for the `val()` why not use `var conceptVal = $("#aioConceptName option").filter(":selected").val();`? – Tester Aug 06 '13 at 21:19
  • 89
    How about a simpler `var conceptVal = $("#aioConceptName option:selected").val()`? – Klemen Tusar Nov 22 '13 at 11:53
  • @techouse That may look simpler, but Web Storm tells your method is "inefficient use of jQuery" and recommends breaking it up. Which I'm actually curious as to why. Must be Crockford's orders. – nzondlo Jan 17 '14 at 13:40
  • Other option would be: `var text = $("select#my_id option:selected").text()` (not using `.val()` as said by @techouse). – Diego Mar 05 '14 at 16:05
  • @DiegoLago: Actually, it's not the `.val()` that's the issue there, so replacing it with `.text()` doesn't make much of a difference. The drawback is the long selector, I believe. – Elliot Bonneville Mar 05 '14 at 16:39
  • 7
    I still found this helpful for finding the selected option in a select where I've obtained the dropdown previously -- e.g., `var mySelect = $('#mySelect');` _/* ... more code happens ... */_ `var selectedText = mySelect.find(':selected').text();` – Charles Wood Jul 10 '14 at 21:34
  • `.val` works with ` – jonasespelita Jul 23 '14 at 10:07
  • Or we could just use - `$('#aioConceptName option:selected').text()` or `$('#aioConceptName :selected').text()` – Amit Dash Sep 01 '14 at 06:45
  • 1
    I had extra data values in my option that I needed to access, like ``, and like @Curious, I also already had the control passed into a jQuery variable, so using `contact_element.find(":selected").data("email")` worked great for me. – furman87 Oct 29 '14 at 12:30
  • $(this).find("option:selected") – Donato May 27 '15 at 22:53
  • 28
    Actually the reason .val() isn't working for him is because he didn't actually give his options a value, which is why he has to use your method to retrieve the selected text, so another fix would've been to change to Although your solution is probably quicker and more practical, I figured I'd state this anyways so he has a better understanding of why it wasn't working for him. – Jordan LaPrise Mar 23 '16 at 23:14
  • Probably good to know that **setting the select option** by value works by using `$("#selector").val("2");` or `$("#selector option[value='2']").prop('selected', true);` and by its text instead: https://stackoverflow.com/q/496052/1066234 – Avatar Jul 19 '17 at 22:32
  • Any idea how can I get the value of any option not just the selected option? – Krishnaveni B Nov 15 '17 at 21:00
  • @KrishnaveniB You can access all the options in an array by doing `$("#aioConceptName").find("option")`. To access a specific child's value, use `$("#aioConceptName").find("option")[0].value`. – Elliot Bonneville Nov 18 '17 at 14:54
  • 2
    This answer is wrong. If an option doesn't have a `value` attribute, its value defaults to its text. And the value of a ` – Barmar Aug 24 '18 at 16:29
  • One of the best too is to always add the option `value` to each `option` tag so you can get value from `$('#aioConceptName').val();`. And of course you can pass the value into hidden input by detecting `onchange` on `#aioConceptName`. I like this answer from @ElliotBonneville to gives you the solution. – FSodic Jul 01 '21 at 10:03
424

Set the values for each of the options

<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
    <option value="0">choose io</option>
    <option value="1">roma</option>
    <option value="2">totti</option>
</select>

$('#aioConceptName').val() didn't work because .val() returns the value attribute. To have it work properly, the value attributes must be set on each <option>.

Now you can call $('#aioConceptName').val() instead of all this :selected voodoo being suggested by others.

Andy
  • 4,783
  • 2
  • 26
  • 51
Jacob Valenta
  • 6,659
  • 8
  • 31
  • 42
  • 16
    Caveat: if no option is selected, `$('#aioConceptName').val()` returns null/"undefined" – gordon Feb 24 '14 at 18:47
  • This assured me that $('#myselect').val() was correct I'd just dumbly forgotten to give the select an id! – zzapper Jun 30 '14 at 17:19
  • 4
    One of my select options is a special `prompt` option ``. In my case it wasn't a problem to add a blank value attribute `` but I believe in some cases not having a value attribute makes sense. But +1 because your vodoo wording made me smile. – Cyril Duchon-Doris Apr 11 '16 at 22:31
  • Isn't `val()` select the `value` instead of the text inside the `option`? I.e. it selects `1` instead of `roma`. – deathlock Oct 29 '17 at 17:31
  • 4
    @deathlock That's the whole point of `.val()`. If you are looking to manipulate/use the text, use `$(":selected).text()` or set the value and the text to be the same. – Jacob Valenta Oct 29 '17 at 19:41
206

I stumbled across this question and developed a more concise version of Elliot BOnneville's answer:

var conceptName = $('#aioConceptName :selected').text();

or generically:

$('#id :pseudoclass')

This saves you an extra jQuery call, selects everything in one shot, and is more clear (my opinion).

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
Ed Orsi
  • 2,265
  • 1
  • 18
  • 18
  • 1
    @JohnConde The accepted answer on Meta disagrees with you: http://meta.stackexchange.com/questions/87678/discouraging-w3schools-as-a-resource . In my opinion, Ed has given a good answer and just provided some extra reference. – itsbruce Nov 01 '12 at 17:38
  • They can allow it but it's still a bad resource – John Conde Nov 01 '12 at 17:41
  • 1
    Removed the w3schools link, it wasn't strictly necessary and a Google search for "jQuery pseduo classes" provides plenty of information. – Ed Orsi Nov 01 '12 at 17:45
  • @EdOrsi: While it saves an extra jQuery call, it prevents from taking taking advantage of the performance boost provided by the native DOM `querySelectorAll()` method (see [jQuery docs](https://api.jquery.com/selected-selector/)). So, it should be slower than the [Eliot's solution](http://stackoverflow.com/a/10659117/3345644). – Alexander Abakumov Nov 30 '15 at 14:56
  • I'd probably favor using `.find(':selected')` as then it allows you do call it from a callback attached to an event... like `$('#aioConceptname').bind('change', function(el) { console.log ( $(el).find(':selected').text() ); });` – Armstrongest Dec 09 '17 at 06:08
  • @AlexanderAbakumov : Cuz `:selected` is a jQuery **extension** and is thus slow, we can use `:checked` instead. `:checked` maps to the in-built CSS functionality, and so does not take the performance hit that `:selected` takes. – Ankit Raj Goyal May 21 '22 at 07:31
73

Try this for value...

$("select#id_of_select_element option").filter(":selected").val();

or this for text...

$("select#id_of_select_element option").filter(":selected").text();
Vladimir Djuricic
  • 4,323
  • 1
  • 21
  • 22
65

If you are in event context, in jQuery, you can retrieve the selected option element using :
$(this).find('option:selected') like this :

$('dropdown_selector').change(function() {
    //Use $option (with the "$") to see that the variable is a jQuery object
    var $option = $(this).find('option:selected');
    //Added with the EDIT
    var value = $option.val();//to get content of "value" attrib
    var text = $option.text();//to get <option>Text</option> content
});

Edit

As mentioned by PossessWithin, My answer just answer to the question : How to select selected "Option".

Next, to get the option value, use option.val().

Community
  • 1
  • 1
JoDev
  • 6,633
  • 1
  • 22
  • 37
  • 4
    Flawless! Just do not forget you should add `$(this).find('option:selected').val()` at the end to get the value of the option element, or `$(this).find('option:selected').text()` to get the text. :) – Diego Fortes May 12 '17 at 15:45
  • The most elegant and simple answer. – andreszs Jul 30 '22 at 14:03
  • These days, you could add "event" as a parameter for that anonymous function, and then get the value of the select list on change using "event.target.value" – D. Cook Sep 28 '22 at 01:30
40

Have you considered using plain old javascript?

var box = document.getElementById('aioConceptName');

conceptName = box.options[box.selectedIndex].text;

See also Getting an option text/value with JavaScript

Community
  • 1
  • 1
Roonaan
  • 1,066
  • 8
  • 11
35
$('#aioConceptName option:selected').val();
wild_nothing
  • 2,845
  • 1
  • 35
  • 47
  • 3
    This is best answer of all, wish there was a way at stack overflow to request to show up the correct answers at the top. – Smitt Mar 21 '21 at 19:26
21

With JQuery:

  1. If you want to get the selected option text, you can use $(select element).text().

    var text = $('#aioConceptName option:selected').text();

  2. If you want to get selected option value, you can use $(select element).val().

    var val = $('#aioConceptName option:selected').val();

    Make sure to set value attribute in <option> tag, like:

    <select id="aioConceptName">
      <option value="">choose io</option>
      <option value="roma(value)">roma(text)</option>
      <option value="totti(value)">totti(text)</option>
    </select>
    

With this HTML code sample, assuming last option is selected:

  1. var text will give you totti(text)
  2. var val will give you totti(value)

$(document).on('change','#aioConceptName' ,function(){
  var val = $('#aioConceptName option:selected').val();
  var text = $('#aioConceptName option:selected').text();
  $('.result').text("Select Value = " + val);
  $('.result').append("<br>Select Text = " + text);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="aioConceptName">
 <option value="io(value)">choose io</option>
 <option value="roma(value)">roma(text)</option>
 <option value="totti(value)">totti(text)</option>
</select>

<p class="result"></p>
NcXNaV
  • 1,657
  • 4
  • 14
  • 23
20

For good practice you need to use val() to get value of selected options not text().

<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
    <option value="choose">choose io</option>
</select>

You can use

   $("#aioConceptName").find(':selected').val();

Or

   $("#aioConceptName :selected").val();
Eric
  • 940
  • 12
  • 27
Yusuf Azan
  • 236
  • 2
  • 7
18

Reading the value (not the text) of a select:

var status = $("#Status").val();
var status = $("#Status")[0].value;
var status = $('#Status option:selected').val();

How to disable a select? in both variants, value can be changed using:

A

User can not interact with the dropdown. And he doesn't know what other options might exists.

$('#Status').prop('disabled', true);

B

User can see the options in the dropdown but all of them are disabled:

$('#Status option').attr('disabled', true);

In this case, $("#Status").val() will only work for jQuery versions smaller than 1.9.0. All other variants will work.

How to update a disabled select?

From code behind you can still update the value in your select. It is disabled only for users:

$("#Status").val(2);

In some cases you might need to fire events:

$("#Status").val(2).change();
kupendra
  • 1,002
  • 1
  • 15
  • 37
profimedica
  • 2,716
  • 31
  • 41
15

you should use this syntax:

var value = $('#Id :selected').val();

So try this Code:

var values = $('#aioConceptName :selected').val();

you can test in Fiddle: http://jsfiddle.net/PJT6r/9/

see about this answer in this post

D.L.MAN
  • 990
  • 12
  • 18
14

to find correct selections with jQuery consider multiple selections can be available in html trees and confuse your expected output.

(:selected).val() or (:selected).text() will not work correct on multiple select options. So we keep an array of all selections first like .map() could do and then return the desired argument or text.

The following example illustrates those problems and offers a better approach

<select id="form-s" multiple="multiple">
    <option selected>city1</option>
    <option selected value="c2">city2</option>
    <option value="c3">city3</option>
</select>   
<select id="aioConceptName">
    <option value="s1" selected >choose io</option>
    <option value="s2">roma </option>
    <option value="s3">totti</option>
</select>
<select id="test">
    <option value="s4">paloma</option>
    <option value="s5" selected >foo</option>
    <option value="s6">bar</option>
</select>
<script>
$('select').change(function() {
    var a=$(':selected').text(); // "city1city2choose iofoo"
    var b=$(':selected').val();  // "city1" - selects just first query !
    //but..
    var c=$(':selected').map(function(){ // ["city1","city2","choose io","foo"]
        return $(this).text();
    }); 
    var d=$(':selected').map(function(){ // ["city1","c2","s1","s5"]
        return $(this).val();
    });
    console.log(a,b,c,d);
});
</script>

see the different bug prone output in variant a, b compared to correctly working c & d that keep all selections in an array and then return what you look for.

Ol Sen
  • 3,163
  • 2
  • 21
  • 30
13

Using jQuery, just add a change event and get selected value or text within that handler.

If you need selected text, please use this code:

$("#aioConceptName").change(function () {
    alert($("#aioConceptName :selected").text())
});

Or if you need selected value, please use this code:

$("#aioConceptName").change(function () {
    alert($("#aioConceptName :selected").attr('value'))
});
sanman
  • 770
  • 1
  • 7
  • 15
13

Just this should work:

var conceptName = $('#aioConceptName').val();

$(function() {
  $('#aioConceptName').on('change', function(event) {
    console.log(event.type + " event with:", $(this).val());
    $(this).prev('input').val($(this).val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
  <option>choose io</option>
  <option>roma</option>
  <option>totti</option>
</select>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
d.popov
  • 4,175
  • 1
  • 36
  • 47
11

For anyone who found out that best answer don't work.

Try to use:

  $( "#aioConceptName option:selected" ).attr("value");

Works for me in recent projects so it is worth to look on it.

StarsSky
  • 6,721
  • 6
  • 38
  • 63
user2709153
  • 325
  • 3
  • 6
10

Use the jQuery.val() function for select elements, too:

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.

$(function() {
  $("#aioConceptName").on("change", function() {
    $("#debug").text($("#aioConceptName").val());
  }).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<select id="aioConceptName">
  <option>choose io</option>
  <option>roma</option>
  <option>totti</option>
</select>
<div id="debug"></div>
Salman A
  • 262,204
  • 82
  • 430
  • 521
10

Straight forward and pretty easy:

Your dropdown

<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>

Jquery code to get the selected value

$('#aioConceptName').change(function() {
    var $option = $(this).find('option:selected');

    //Added with the EDIT
    var value = $option.val(); //returns the value of the selected option.
    var text = $option.text(); //returns the text of the selected option.
});
Juan J
  • 413
  • 6
  • 12
10

For get value of tag selected:

 $('#id_Of_Parent_Selected_Tag').find(":selected").val();

And if you want to get text use this code:

 $('#id_Of_Parent_Selected_Tag').find(":selected").text();

For Example:

<div id="i_am_parent_of_select_tag">
<select>
        <option value="1">CR7</option>
        <option value="2">MESSI</option>
</select>
</div>


<script>
 $('#i_am_parent_of_select_tag').find(":selected").val();//OUTPUT:1 OR 2
 $('#i_am_parent_of_select_tag').find(":selected").text();//OUTPUT:CR7 OR MESSI
</script>
mamal
  • 1,791
  • 20
  • 14
5

I hope this also helps to understand better and helps try this below,

$('select[id="aioConceptName[]"] option:selected').each(function(key,value){
   options2[$(this).val()] = $(this).text();
   console.log(JSON.stringify(options2));
});

to more details please http://www.drtuts.com/get-value-multi-select-dropdown-without-value-attribute-using-jquery/

Rashed Hasan
  • 3,721
  • 11
  • 40
  • 82
Vijayaragavan
  • 919
  • 1
  • 8
  • 8
5

You can try to debug it this way:

console.log($('#aioConceptName option:selected').val())
DaFois
  • 2,197
  • 8
  • 26
  • 43
swathi
  • 97
  • 1
  • 2
4

If you want to grab the 'value' attribute instead of the text node, this will work for you:

var conceptName = $('#aioConceptName').find(":selected").attr('value');
Drodarious
  • 86
  • 3
  • This is only partially a solution - it is also necessary to set the value for each option - this is already covered by Jacob Valetta's answer – David Oct 27 '16 at 00:42
4

Here is the simple solution for this issue.

$("select#aioConceptName").change(function () {
           var selectedaioConceptName = $('#aioConceptName').find(":selected").val();;
           console.log(selectedaioConceptName);
        });
Sanjaya
  • 195
  • 1
  • 13
  • 1
    ```var selectedaioConceptName = $('#aioConceptName option:selected').val();``` is better than use another find() – Sadee May 20 '20 at 22:46
4

You many try this:

var ioConceptName = $('#ioConceptName option:selected').text(); 
Esset
  • 916
  • 2
  • 15
  • 17
Rosh
  • 41
  • 3
3

try to this one

$(document).ready(function() {

    $("#name option").filter(function() {
        return $(this).val() == $("#firstname").val();
    }).attr('selected', true);

    $("#name").live("change", function() {

        $("#firstname").val($(this).find("option:selected").attr("value"));
    });
});


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<select id="name" name="name"> 
<option value="">Please select...</option> 
<option value="Elvis">Elvis</option> 
<option value="Frank">Frank</option> 
<option value="Jim">Jim</option> 
</select>

<input type="text" id="firstname" name="firstname" value="Elvis" readonly="readonly">
3
$('nameofDropDownList').prop('selectedIndex', whateverNumberasInt);

Imagine the DDL as an array with indexes, you are selecting one index. Choose the one which you want to set it to with your JS.

Satista
  • 31
  • 3
2

You can use $("#drpList").val();

Ankur Soni
  • 5,725
  • 5
  • 50
  • 81
Praveen Patel G
  • 342
  • 4
  • 13
2

to fetch a select with same class= name you could do this, to check if a select option is selected.

var bOK = true;
$('.optKategorien').each(function(index,el){
    if($(el).find(":selected").text() == "") {
        bOK = false;
    }
});
Jan Bludau
  • 321
  • 4
  • 11
2

I had the same issue and I figured out why it was not working on my case
The html page was divided into different html fragments and I found that I have another input field that carries the same Id of the select, which caused the val() to be always empty
I hope this saves the day for anyone who have similar issue.

Hasnaa Ibraheem
  • 1,132
  • 1
  • 10
  • 18
  • Indeed, this woke me to my problem. I was myself using qty-field in the data-target and.. qty_field in the id itself. Always check the basics twice or more. – cdsaenz May 31 '20 at 18:20
2

Try

aioConceptName.selectedOptions[0].value

let val = aioConceptName.selectedOptions[0].value

console.log('selected value:',val);
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2

There is only one correct way to find selected option - by option value attribute. So take the simple code:

//find selected option
$select = $("#mySelect");
$selectedOption = $select.find( "option[value=" + $select.val() + "]" );
//get selected option text
console.log( $selectedOption.text() );

So if you have list like this:

<select id="#mySelect" >
  <option value="value1" >First option</option>
  <option value="value2" >Second option</option>
  <option value="value3" selected >Third option</option>
</select>

If you use selected attribute for option, then find(":selected") will give incorrect result because selected attribute will stay at option forever, even user selects another option.

Even if user will selects first or second option, the result of $("select option:selected") will give two elements! So $("select :selected").text() will give a result like "First option Third option"

So use value attribute selector and don't forget to set value attribute for all options!

1

Probably your best bet with this kind of scenario is to use jQuery's change method to find the currently selected value, like so:

$('#aioConceptName').change(function(){

   //get the selected val using jQuery's 'this' method and assign to a var
   var selectedVal = $(this).val();

   //perform the rest of your operations using aforementioned var

});

I prefer this method because you can then perform functions for each selected option in a given select field.

Hope that helps!

1

Usually you'd need to not only get the selected value, but also run some action. So why not avoid all the jQuery magic and just pass the selected value as an argument to the action call?

<select onchange="your_action(this.value)">
   <option value='*'>All</option>
   <option ... />
</select>
Roland
  • 4,619
  • 7
  • 49
  • 81
1

You can select using exact selected option : Below will give innerText

$("select#aioConceptName > option:selected").text()

While below will give you value.

$("select#aioConceptName > option:selected").val()
Hafiz Shehbaz Ali
  • 2,566
  • 25
  • 21
1

try this code: :)

get value:

 $("#Ostans option:selected").val() + '.' + $("#shahrha option:selected").val()

get text:

 $("#Ostans option:selected").text() + '.' + $("#shahrha option:selected").text()
Mojtaba Nava
  • 858
  • 7
  • 17
1
  1. Use name attribute of the select element.

    <select name="myName"></select>

  2. $('select[name=myName]').val()

Sandee007
  • 141
  • 2
  • 7