Here are two methods for getting the value of the selected option in a dropdown (select
element).
This can be useful for performing various actions in real-time (on change, as the user selects an option).
Method 1: addEventListener
The first method is using an event listener in JavaScript.
HTML
<div class="form-group">
<select id="category" name="category" class="form-control">
<option value hidden disabled selected></option>
<option value="category_a">Category A</option>
<option value="category_b">Category B</option>
</select>
<label for="category">Category</label>
</div>
JavaScript
const categorySelect = document.querySelector('select#category');
categorySelect.addEventListener('change', (e) => {
const selectedCategory = e.target.value;
if (selectedCategory === 'category_a') {
// Do something.
}
});
Method 2: onchange
The second method is using the onchange
attribute, directly on the select
element.
HTML
Notice the onchange="updateCategory(this)"
on the select
element.
Here we pass the whole field (this
= the select
element) to the JS function (updateCategory
).
<div class="form-group">
<select
id="category"
name="category"
class="form-control"
onchange="updateCategory(this)"
>
<option value hidden disabled selected></option>
<option value="category_a">Category A</option>
<option value="category_b">Category B</option>
</select>
<label for="category">Category</label>
</div>
JavaScript
Then, in JS we can extract and use only the current value of the select element (field.value
) or other parameters as well.
function updateCategory(field) {
const selectedCategory = field.value;
if (selectedCategory === 'category_a') {
// Do something.
}
}
Alternatively, we can pass only the value of the selected option (this.value
), instead of the entire field:
HTML
<div class="form-group">
<select
id="category"
name="category"
class="form-control"
onchange="updateCategory(this.value)"
>
<option value hidden disabled selected></option>
<option value="category_a">Category A</option>
<option value="category_b">Category B</option>
</select>
<label for="category">Category</label>
</div>
JavaScript
function updateCategory(selectedCategory) {
if (selectedCategory === 'category_a') {
// Do something.
}
}