I am trying to grab the value of my dropdown list and store it in a variable using Javascript. I have searched several articles and have mostly found JQuery methods (methods that have not worked for me, I could be implementing them incorrectly), but I would prefer using a pure Javascript method.
Solution reviewed:
Get selected value in dropdown list using JavaScript
This solution using an <option>
HTML tag as where I am using a <div>
tag.
I have also implemented a JQuery function that allows the selected value in the dropdown to replace the button text, could this be intervening with my ability to implement the functionality of grabbing that value?
All solutions I seem to be looking for contain the option
tag.
JS:
let valueElement = document.querySelector(".dropdown-menu");
let strUsers = valueElement.option[valueElement.selectedIndex].text;
console.log(`User Selected: ${strUsers}`)
I should probably not be using .option
HTML:
<div class="btn-group">
<button class="btn btn-info dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
User
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu1">
<a class="dropdown-item" href="#" data-value="Admin-0">Admin-0</a>
<a class="dropdown-item" href="#" data-value="Admin-1">Admin-1</a>
<a class="dropdown-item" href="#" data-value="Admin-2">Admin-2</a>
</div>
</div>