2186

How do I get the selected value from a dropdown list using JavaScript?

I tried the methods below, but they all return the selected index instead of the value:

var e = document.getElementById("ddlViewBy");
function show(){
  var as = document.forms[0].ddlViewBy.value;
  var strUser = e.options[e.selectedIndex].value;
  console.log(as, strUser);
}
e.onchange=show;
show();
<form>
  <select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
  </select>
</form>
Lakshya Raj
  • 1,094
  • 4
  • 20
Fire Hand
  • 23,886
  • 22
  • 49
  • 74

31 Answers31

3469

If you have a select element that looks like this:

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

Running this code:

var e = document.getElementById("ddlViewBy");
var strUser = e.value;

Would make strUser be 2. If what you actually want is test2, then do this:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;

Which would make strUser be test2

DevLoverUmar
  • 8,356
  • 8
  • 44
  • 81
Paolo Bergantino
  • 466,948
  • 77
  • 516
  • 433
  • I am writing the exactly same code BUT inside a function in script tag. When the user will select that option from the drop-down menu, then I should be getting the text. So should I be using onclick/ontoggle/onchange ?Which of the one ? – R11G Dec 12 '13 at 14:04
  • 166
    `var strUser = e.options[e.selectedIndex].value;` why not just `var strUser = e.value ?` – The Red Pea Dec 31 '14 at 00:01
  • 25
    @TheRedPea—perhaps because when this answer was written there was a chance (however remote) that an ancient version of Netscape Navigator needed to be accommodated, so an equally ancient method for accessing the value of a single select was used. But I'm just guessing about that. ;-) – RobG Jan 18 '15 at 04:06
  • 15
    I used like this: `var e = document.getElementById("ddlViewBy").value;` – Fthr Oct 25 '16 at 16:16
  • @RishiDua you can iterate the options of the select: `for(var o of e.options) { if (o.selected) { /* ... */ } }` – Massimiliano Kraus Dec 29 '17 at 10:42
  • Good answer but this doesn't work well for a multi select. Can someone assist? – Harold_Finch Jun 14 '18 at 13:27
  • 1
    @Harold_Finch for(var o of e.options) { if (o.selected) { /* ... */ } } solution should work, although I dont remember what I did (2yr old comment). – Rishi Dua Jun 14 '18 at 22:53
  • 5
    should be `e.target.options[e.target.selectedIndex].text` don't know why it's wrong in all answers here.. – OZZIE Jan 02 '19 at 11:10
  • `e.val()` was enough for me – Salam Oct 10 '19 at 05:46
  • Purists would even write `const e = document.getElementById("ddlViewBy");` since it will not change (it's a DOM assumption) – Fabien Haddadi Nov 26 '19 at 12:12
  • 3
    @OZZIE - Look at the assignment statement beginning with `var e` in the OP's question. While it's convention for `e` (or `event`) to represent the `eventObject`, here the OP is using it to represent the element. – Rounin - Standing with Ukraine Jan 28 '20 at 14:24
  • @Salam That's jQuery, not plain JavaScript. – ygoe Jan 18 '22 at 15:42
438

Plain JavaScript:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

jQuery:

$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").val(); // The value of the selected option

AngularJS: (http://jsfiddle.net/qk5wwyct):

// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>

// JavaScript
$scope.items = [{
  value: 'item_1_id',
  text: 'Item 1'
}, {
  value: 'item_2_id',
  text: 'Item 2'
}];
Machtyn
  • 2,432
  • 5
  • 30
  • 51
Vitalii Fedorenko
  • 104,478
  • 28
  • 147
  • 111
  • 2
    I must be doing something wrong because when I try this I get back the text of every option in the drop down. – Kevin Jun 06 '13 at 21:18
  • 6
    This did worked for me in different way. $("#ddlViewBy :selected").val() not without selected – Ruwantha Aug 14 '13 at 08:07
  • 1
    `element.options[e.selectedIndex].value` must be `element.options[element.selectedIndex].value` – Christopher Mar 27 '15 at 15:18
  • Still useful - thank you for writing out the variations / language! Now if I only knew the equivalent for Office JS API Dropdown... – Cindy Meister Mar 01 '18 at 18:21
  • should be `e.target.options[e.target.selectedIndex].text` don't know why it's wrong in all answers here.. – OZZIE Jan 02 '19 at 11:10
  • 1
    It also worked for me in jQuery by simply putting `$("#elementId").val()` with no need to mention the `selected` – Elias Mar 16 '21 at 23:29
191
var strUser = e.options[e.selectedIndex].value;

This is correct and should give you the value. Is it the text you're after?

var strUser = e.options[e.selectedIndex].text;

So you're clear on the terminology:

<select>
    <option value="hello">Hello World</option>
</select>

This option has:

  • Index = 0
  • Value = hello
  • Text = Hello World
Greg
  • 307,243
  • 53
  • 363
  • 328
  • 1
    i thought the ".value" in javascript should returns the value for me but only the ".text" would returns as what the .SelectedValue in asp.net returns. Thanks for example given! – Fire Hand Jul 06 '09 at 07:56
  • 1
    Yep - make the value of the option the same as what it is. Simpler - the guy above needs to write more code to make up for his initial vagueness. – Andrew Koper Aug 27 '13 at 15:00
  • should be `e.target.options[e.target.selectedIndex].text` don't know why it's wrong in all answers here.. – OZZIE Jan 02 '19 at 11:10
68

The following code exhibits various examples related to getting/putting of values from input/select fields using JavaScript.

Source Link

Working Javascript & jQuery Demo

enter image description here

enter image description here

 <select id="Ultra" onchange="run()">  <!--Call run() function-->
     <option value="0">Select</option>
     <option value="8">text1</option>
     <option value="5">text2</option>
     <option value="4">text3</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
TextBox2<br>
<input type="text" id="rtt"  placeholder="Write Something !" onkeyup="up()">

The following script is getting the value of the selected option and putting it in text box 1

<script>
    function run() {
        document.getElementById("srt").value = document.getElementById("Ultra").value;
    }
</script>

The following script is getting a value from a text box 2 and alerting with its value

<script>
    function up() {
        //if (document.getElementById("srt").value != "") {
            var dop = document.getElementById("srt").value;
        //}
        alert(dop);
    }
</script>

The following script is calling a function from a function

<script>
    function up() {
        var dop = document.getElementById("srt").value;
        pop(dop); // Calling function pop
    }

    function pop(val) {
        alert(val);
    }?
</script>
Code Spy
  • 8,830
  • 4
  • 62
  • 44
52
var selectedValue = document.getElementById("ddlViewBy").value;
Bucket
  • 7,139
  • 9
  • 32
  • 45
Mohammad Faisal
  • 1,929
  • 1
  • 18
  • 14
  • 5
    This is the simplest solution, at least for modern browsers. See also [W3Schools](https://www.w3schools.com/jsref/prop_select_value.asp). – Erik Koopmans Sep 11 '18 at 02:14
26

If you ever run across code written purely for Internet Explorer you might see this:

var e = document.getElementById("ddlViewBy");
var strUser = e.options(e.selectedIndex).value;

Running the above in Firefox et al will give you an 'is not a function' error, because Internet Explorer allows you to get away with using () instead of []:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

The correct way is to use square brackets.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Carl Onager
  • 4,001
  • 2
  • 35
  • 65
21
<select id="Ultra" onchange="alert(this.value)"> 
 <option value="0">Select</option>
 <option value="8">text1</option>
 <option value="5">text2</option>
 <option value="4">text3</option>
</select>

Any input/form field can use a “this” keyword when you are accessing it from inside the element. This eliminates the need for locating a form in the dom tree and then locating this element inside the form.

boateng
  • 864
  • 11
  • 21
19

There are two ways to get this done either using JavaScript or jQuery.

JavaScript:

var getValue = document.getElementById('ddlViewBy').selectedOptions[0].value;

alert (getValue); // This will output the value selected.

OR

var ddlViewBy = document.getElementById('ddlViewBy');

var value = ddlViewBy.options[ddlViewBy.selectedIndex].value;

var text = ddlViewBy.options[ddlViewBy.selectedIndex].text;

alert (value); // This will output the value selected

alert (text); // This will output the text of the value selected

jQuery:

$("#ddlViewBy:selected").text(); // Text of the selected value

$("#ddlViewBy").val(); // Outputs the value of the ID in 'ddlViewBy'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Du-Lacoste
  • 9,842
  • 2
  • 62
  • 47
18

Beginners are likely to want to access values from a select with the NAME attribute rather than ID attribute. We know all form elements need names, even before they get ids.

So, I'm adding the getElementsByName() solution just for new developers to see too.

NB. names for form elements will need to be unique for your form to be usable once posted, but the DOM can allow a name be shared by more than one element. For that reason consider adding IDs to forms if you can, or be explicit with form element names my_nth_select_named_x and my_nth_text_input_named_y.

Example using getElementsByName:

var e = document.getElementsByName("my_select_with_name_ddlViewBy")[0];
var strUser = e.options[e.selectedIndex].value;
Ben Greenaway
  • 181
  • 1
  • 2
  • Doesn't work if my_select_with_name_ddlViewBy is an array like my_select_with_name_ddlViewBy[] – zeuf Dec 09 '17 at 17:44
14

Just use

  • $('#SelectBoxId option:selected').text(); for getting the text as listed

  • $('#SelectBoxId').val(); for getting the selected index value

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Marvil Joy
  • 652
  • 6
  • 14
12

I don't know if I'm the one that doesn't get the question right, but this just worked for me: Use an onchange() event in your HTML, eg.

<select id="numberToSelect" onchange="selectNum()">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

//javascript

function selectNum(){
    var strUser = document.getElementById("numberToSelect").value;
}

This will give you whatever value is on the select dropdown per click

John Codeos
  • 1,031
  • 1
  • 12
  • 17
Olawale Oladiran
  • 455
  • 1
  • 10
  • 19
9

The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id versus name. One can get a read-out of three data of a selected option -- its index number, its value and its text. This simple, cross-browser code does all three:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo GetSelectOptionData</title>
</head>
<body>
    <form name="demoForm">
        <select name="demoSelect" onchange="showData()">
            <option value="zilch">Select:</option>
            <option value="A">Option 1</option>
            <option value="B">Option 2</option>
            <option value="C">Option 3</option>
        </select>
    </form>

    <p id="firstP">&nbsp;</p>
    <p id="secondP">&nbsp;</p>
    <p id="thirdP">&nbsp;</p>

    <script>
    function showData() {
        var theSelect = demoForm.demoSelect;
        var firstP = document.getElementById('firstP');
        var secondP = document.getElementById('secondP');
        var thirdP = document.getElementById('thirdP');
        firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
        secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
        thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
    }
     </script>
</body>
</html>

Live demo: http://jsbin.com/jiwena/1/edit?html,output .

id should be used for make-up purposes. For functional form purposes, name is still valid, also in HTML5, and should still be used. Lastly, mind the use of square versus round brackets in certain places. As was explained before, only (older versions of) Internet Explorer will accept round ones in all places.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
9

Using jQuery:

$('select').val();
8

Another solution is:

document.getElementById('elementId').selectedOptions[0].value
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Javad Kargar
  • 1,053
  • 1
  • 10
  • 24
7

You can use querySelector.

E.g.

var myElement = document.getElementById('ddlViewBy');

var myValue = myElement.querySelector('[selected]').value;
7

The simplest way to do this is:

var value = document.getElementById("selectId").value;
Clairton Luz
  • 1,870
  • 18
  • 15
6

Running example of how it works:

var e = document.getElementById("ddlViewBy");
var val1 = e.options[e.selectedIndex].value;
var txt = e.options[e.selectedIndex].text;

document.write("<br />Selected option Value: "+ val1);
document.write("<br />Selected option Text: "+ txt);
<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2">test2</option>
  <option value="3"  selected="selected">test3</option>
</select>

Note: The values don't change as the dropdown is changed, if you require that functionality then an onClick change is to be implemented.

Ani Menon
  • 25,420
  • 16
  • 92
  • 119
5

To go along with the previous answers, this is how I do it as a one-liner. This is for getting the actual text of the selected option. There are good examples for getting the index number already. (And for the text, I just wanted to show this way)

let selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text

In some rare instances you may need to use parentheses, but this would be very rare.

let selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;

I doubt this processes any faster than the two line version. I simply like to consolidate my code as much as possible.

Unfortunately this still fetches the element twice, which is not ideal. A method that only grabs the element once would be more useful, but I have not figured that out yet, in regards to doing this with one line of code.

Genko
  • 345
  • 4
  • 10
5

I have a bit different view of how to achieve this. I'm usually doing this with the following approach (it is an easier way and works with every browser as far as I know):

<select onChange="functionToCall(this.value);" id="ddlViewBy">
  <option value="value1">Text one</option>
  <option value="value2">Text two</option>
  <option value="value3">Text three</option>
  <option value="valueN">Text N</option>
</select>
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ThomAce
  • 271
  • 4
  • 7
4

In 2015, in Firefox, the following also works.

e.options.selectedIndex

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
4

In more modern browsers, querySelector allows us to retrieve the selected option in one statement, using the :checked pseudo-class. From the selected option, we can gather whatever information we need:

const opt = document.querySelector('#ddlViewBy option:checked');
// opt is now the selected option, so
console.log(opt.value, 'is the selected value');
console.log(opt.text, "is the selected option's text");
<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>
Heretic Monkey
  • 11,078
  • 7
  • 55
  • 112
3

Here is a JavaScript code line:

var x = document.form1.list.value;

Assuming that the dropdown menu named list name="list" and included in a form with name attribute name="form1".

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Belgacem Ksiksi
  • 264
  • 1
  • 5
  • 20
  • OP said that didn't work for them: "I tried the methods below but they all return the selected index instead of the value: `var as = document.form1.ddlViewBy.value;`..." – ReinstateMonica3167040 Jul 16 '18 at 23:38
3

You should be using querySelector to achieve this. This also standardize the way of getting value from form elements.

var dropDownValue = document.querySelector('#ddlViewBy').value;

Fiddle: https://jsfiddle.net/3t80pubr/

Pal Singh
  • 1,941
  • 1
  • 14
  • 28
3

event.target.value inside the onChange callback did the trick for me.

emptywalls
  • 1,187
  • 10
  • 14
2

Try

ddlViewBy.value                      // value

ddlViewBy.selectedOptions[0].text    // label

console.log( ddlViewBy.value );

console.log( ddlViewBy.selectedOptions[0].text );
<select id="ddlViewBy">
  <option value="1">Happy</option>
  <option value="2">Tree</option>
  <option value="3"  selected="selected">Friends</option>
</select>
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
2

I think you can attach an event listener to the select tag itself e.g:

<script>
  document.addEventListener("DOMContentLoaded", (_) => {
    document.querySelector("select").addEventListener("change", (e) => {
      console.log(e.target.value);
    });
  });
</script>

In this scenario, you should make sure you have a value attribute for all of your options, and they are not null.

Mario Petrovic
  • 5,868
  • 12
  • 32
  • 54
Emmanuel Onah
  • 421
  • 3
  • 8
  • Great answer, thank you! In my case, I have two selectors, but I was able to access the selector id with 'e.srcElement.id' – Dominic Smith Dec 23 '20 at 15:14
1

Here's an easy way to do it in an onchange function:

event.target.options[event.target.selectedIndex].dataset.name

zackify
  • 5,026
  • 2
  • 19
  • 25
0

Just do: document.getElementById('idselect').options.selectedIndex

Then you i'll get select index value, starting in 0.

Knautiluz
  • 344
  • 3
  • 12
0
<select name="test" id="test" >
    <option value="1" full-name="Apple">A</option>
    <option value="2" full-name="Ball">B</option>
    <option value="3" full-name="Cat" selected>C</option>
</select>

var obj  = document.getElementById('test');
obj.options[obj.selectedIndex].value;  //3
obj.options[obj.selectedIndex].text;   //C
obj.options[obj.selectedIndex].getAttribute('full-name'); //Cat
obj.options[obj.selectedIndex].selected; //true
Dhairya Lakhera
  • 3,932
  • 3
  • 27
  • 47
0

Most answer here get the value of "this" select menu onchange by plain text JavaScript selector.

For example:

document.getElementById("ddlViewBy").value;

This is not DRY approach.

DRY (3 lines of code):

function handleChange(e) {
  let innerText = e.target[e.target.options.selectedIndex].innerText;
  let value = e.target.value;
  /* Do something with these values */
}

Get the first select option:

console.log(e.target[0]); /*output: <option value="value_hello">Hello innerText</option>*/

With this idea in mind we return dynamically "this" select option item (By selectedIndex):

e.target[e.target.options.selectedIndex].innerText;

DEMO

let log = document.getElementById('log');

function handleChange(e) {
  let innerText = e.target[e.target.options.selectedIndex].innerText;
  let value = e.target.value;
  
  log.innerHTML = `<table>
    <tr><th>value</th><th>innerText</th></tr>
    <tr><td>${value}</td><td>${innerText}</td></tr>
  </table>`;

}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.css">

<select id="greet" onchange="handleChange(event)">
  <option value="value_hello">Hello innerText</option>
  <option value="value_goodbye">Goodbye innerText</option>
  <option value="value_seeYou">See you... innerText</option>
</select>

<select id="other_select_menu" onchange="handleChange(event)">
  <option value="value_paris">Paris innerText</option>
  <option value="value_ny">New York innerText</option>
</select>

<div id="log"></div>
Ezra Siton
  • 5,153
  • 2
  • 18
  • 29
-1

Make a drop-down menu with several options (As many as you want!)

<select>
  <option value="giveItAName">Give it a name
  <option value="bananaShark">Ridiculous animal
  <ooption value="Unknown">Give more options!
</select>

I made a bit hilarious. Here's the code snippet:

<select>
  <option value="RidiculousObject">Banana Shark
  <option value="SuperDuperCoding">select tag and option tag!
  <option value="Unknown">Add more tags to add more options!
</select>
<h1>Only 1 option (Useless)</h1>
<select>
  <option value="Single">Single Option
</select>  

yay the snippet worked