How to write JavaScript to get what the selected values in the list

Asked 2 years ago, Updated 2 years ago, 24 views

How do I get the selected value from the list box?

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

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

I tried it like this, but it returns the selected index instead of the value.

javascript html

2022-09-22 21:59

1 Answers

List is

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

If it's like this

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

You can do it like this. And if you want to get the selected text,

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

You can do it like this.


2022-09-22 21:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.