How to retrieve chosen option from select element with JavaScript

I’m working on a web form and need to extract the currently selected option from a dropdown menu using JavaScript. I’ve tried a few approaches but can’t seem to get it working properly.

Here’s my HTML structure:

<div>
  <select id="categoryPicker">
    <option value="apple">Apple</option>
    <option value="banana" selected="selected">Banana</option>
    <option value="orange">Orange</option>
  </select>
</div>

What’s the best way to grab the selected value from this dropdown? I need to use this value in other parts of my JavaScript code. Any help would be appreciated!

To retrieve the selected option’s value from a dropdown, use the value property of the <select> element. Here’s a simple way to do it:

const dropdown = document.getElementById('categoryPicker');
const selectedValue = dropdown.value;
console.log(selectedValue); // This will output 'banana'

This method directly gives you the value of the selected option. If you require the displayed text of the selected option, you can utilize dropdown.options[dropdown.selectedIndex].text. Generally, the value is what you’ll need.

You can also use the selectedIndex property for more control over the selection:

const selectElement = document.getElementById('categoryPicker');
const selectedOption = selectElement.options[selectElement.selectedIndex];
console.log(selectedOption.value); // gets the value
console.log(selectedOption.text);  // gets the display text

This works great when you need both the value and display text, or you’re dealing with dynamically generated options. I use this a lot when option values are IDs but I also need the readable text for other parts of the app.

you can also use querySelector instead of getElementById. just use document.querySelector('#categoryPicker').value - it’ll grab the selected option’s value instantly. same result, but some people like this syntax better.