0 votes
1 view
in Java by (9.2k points)

Below is the code I’ve to select value from a dropdown list using JavaScript: 

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>

When I run the above code, it returns me an index instead of a value. Can anyone tell me what I’m wrong here? 

1 Answer

0 votes
by (19k points)

If you have a code for with ‘select’ element like below: 

<select id="ddlViewBy">

  <option value="1">test1</option>

  <option value="2" selected="selected">test2</option>

  <option value="3">test3</option>

</select>


 

When you run the below code, it’ll make the strUser as 2: 

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

var strUser = e.value;

If you want exactly test2, you can do something like below: 

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

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

Interested in Java? Check out this Java Certification by Intellipaat. 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...