简体   繁体   中英

How to fetch selected option in javascript for more than one dropdowns

I have more than one dropdowns on my page, and I want selected options of each dropdown using their name.

I have tried this method but no success

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

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

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

https://jsfiddle.net/37zg8u5L/1/

If you're going to reference elements by name instead of ID, you can use the code below. But keep in mind the elements will need to be the same name (which can be confusing) and you'll have to memorize the indexes of each element you want to reference, so I would strongly recommend assigning IDs instead. Since you are referencing multiple elements, an array of elements will be returned rather than one, which is why your code broke.

 var e1 = document.getElementsByName("ddlViewBy")[0]; var e2 = document.getElementsByName("ddlViewBy")[1]; var strUser = e1.options[e1.selectedIndex].text; var strUser2 = e2.options[e2.selectedIndex].text; console.log(strUser); console.log(strUser2);
 <select name="ddlViewBy"> <option value="1">test1</option> <option value="2" selected="selected">test2</option> <option value="3">test3</option> </select> <select name="ddlViewBy"> <option value="1" selected="selected">test1</option> <option value="2" >test2</option> <option value="3">test3</option> </select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM