Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected value from Dropdown list in JavaScript

Tags:

javascript

How can you get the selected value from drop down list using JavaScript? I have tried the following but it does not work.

var sel = document.getElementById('select1');
var sv = sel.options[sel.selectedIndex].value;
alert(sv);
like image 806
Somi Meer Avatar asked Jan 12 '12 09:01

Somi Meer


3 Answers

It is working fine with me.

I have the following HTML:

<div>
    <select id="select1">
        <option value="1">test1</option>
        <option value="2" selected="selected">test2</option>
        <option value="3">test3</option>
    </select>
    <br/>
    <button onClick="GetSelectedItem('select1');">Get Selected Item</button>
</div>

And the following JavaScript:

function GetSelectedItem(el)
{
    var e = document.getElementById(el);
    var strSel = "The Value is: " + e.options[e.selectedIndex].value + " and text is: " + e.options[e.selectedIndex].text;
    alert(strSel);
}

See that you are using the right id. In case you are using it with ASP.NET, the id changes when rendered.

like image 163
Kangkan Avatar answered Oct 21 '22 07:10

Kangkan


Direct value should work just fine:

var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

like image 34
Shadow Wizard Hates Omicron Avatar answered Oct 21 '22 06:10

Shadow Wizard Hates Omicron


Hope it's working for you

 function GetSelectedItem()
 {
     var index = document.getElementById(select1).selectedIndex;

     alert("value =" + document.getElementById(select1).value); // show selected value
     alert("text =" + document.getElementById(select1).options[index].text); // show selected text 
 }
like image 2
Kailas Avatar answered Oct 21 '22 07:10

Kailas