Skip to content
Fix Code Error

Get selected value in dropdown list using JavaScript

March 13, 2021 by Code Error
Posted By: Anonymous

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 as = document.form1.ddlViewBy.value;
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

Solution

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

Answered By: Anonymous

Related Articles

  • How to properly do JSON API GET requests and assign output…
  • Pandas pivot_table: filter on aggregate function
  • How to parse JSON with XE2 dbxJSON
  • how to make a conditional multilevel menu with vue.js?
  • Azure Availability Zone ARM Config
  • The 'compilation' argument must be an instance of…
  • Use Combine to route SwiftUI Views
  • Search match multiple values in single field in…
  • NullpointerException error while working with choiceBox and…
  • Form field border-radius is not working only on the last…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I UPDATE from a SELECT in SQL Server?

Next Post:

Finding the index of an item in a list

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error