Home > Blockchain >  Get the selected option inside a <select> tag with javascript
Get the selected option inside a <select> tag with javascript

Time:08-02

Hello I am trying to get the value from a select tag, using javascript, that is generated within a razor view using C#.

This is the html where the select tag is generated:

<form id="asignRol" method="post">
    <select name="users" id="userChange">
        @foreach (var user in Model.UserAndRolesInfo)
        {
            <option value="@user.Username">@user.Username</option>
        }
    </select>

    <select name="rol" id="roleChange">
        @foreach (var rol in @Model.roleAvailability)
        {
            <option value="@rol.Name">@rol.Name</option>
        }
    </select>
    <button type="button" id="submitButton" >Asignar rol</button>
</form>

The html select tag is generated as expected:

HTML phot

In a different js file I am trying to get the values of the selected options:

var submitButton = document.getElementById("submitButton");
var userSelect = document.getElementById("userChange");
var userSelectValue = userSelect.options[userSelect.selectedIndex].value;
var roleSelect = document.getElementById("roleChange");
var roleSelectValue = roleSelect.value;


submitButton.addEventListener("click", function () {
    console.log(userSelectValue);
    console.log(roleSelectValue);
})

With the result of only getting the default value:

Result

I tried passing the event and event.preventdefault.

CodePudding user response:

You need to get the value when the event occurs not before it. In your case event click.

var submitButton = document.getElementById("submitButton");
var userSelect = document.getElementById("userChange");
var roleSelect = document.getElementById("roleChange");

submitButton.addEventListener("click", function() {
  var userSelectValue = userSelect.options[userSelect.selectedIndex].value;
  var roleSelectValue = roleSelect.options[roleSelect.selectedIndex].value;
  console.log(userSelectValue);
  console.log(roleSelectValue);
})
<form id="asignRol" method="post">
  <select name="users" id="userChange">
    <option value="@user.Username">@user.Username</option>
    <option value="moses">moses</option>
    <option value="cat">cat</option>
    <option value="dog">dog</option>
  </select>

  <select name="rol" id="roleChange">
    <option value="@rol.Name">@rol.Name</option>
    <option value="mouse">mouse</option>
    <option value="elephant">elephant</option>
    <option value="fox">fox</option>
  </select>
  <button type="button" id="submitButton" >Asignar rol</button>
</form>

  • Related