简体   繁体   中英

Select Dropdown menu value or text using Javascript

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>

If you create a custom select dropdown, you can not use the selectIndex property because the selectIndex is only available on <select> element, also options property is only available on <select>

https://www.w3schools.com/jsref/prop_select_selectedindex.asp

You need to do something different, you can append an event listener on <a> inside your dropdown and put a class that tell you if user select

I hope it helps

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