0 votes

Get value of select using javascript by name

Good day, I tried to get the selected value of a select using javascript by the name property, can guide me?, I've seen a lot of exercises where it is made by id, but that's what I want by name.

I have the following code but it works for me to get the values by id of the element:

 var selectUser = document.getElementById('User'); var strUser = e.options[e.selectedIndex].value;

What I want is to get the value by using the name of the item, I was doing it the following way, but does not work for me:

 var selectUser = document.getElementByName('User'); var strUser = e.options[e.selectedIndex].value;


enxaneta Points 2355

To select the select element by name you can use:


Here's an example:

var selectUser = document.querySelector("[name='user']"); 
<select name="user">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>


HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by: