Nayantara Wilfred Nayantara Wilfred -5 years ago 143
Javascript Question

Get value selected in dropdown list using Javascript (displays null)

I need to access the value selected from a drop down list using Javascript. But every time I get 'null' as the answer though a list item is selected.

My HTML page:

<select class="mySelect">
<option value="st1" selected="selected">Create new Stream</option>
<option value="st1">Stream 1</option>
<option value="st2">Stream 2</option>
<option value="st3">Stream 3</option>
<option value="st4">Stream 4</option>

<input type="button" value="show attributes" class="panel-button-attr" onclick="choice()">

When the above button is clicked, the selected value should be alerted to the user. So in my Javascript function:

function choice() {

var choice=document.getElementById("mySelect");
var strUser = choice.options[choice.selectedIndex].text;


Here, I've tried to use the first alert to check if any selected list item is identified correctly. But, at this point, it displays null and the strUsr line doesn't run at all.

I know this is actually a trivial task but am finding it hard to figure this inconsistency.

Answer Source

You have to specify id of select element

<select class="mySelect" id="mySelect">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download