I have an HTML element populated with options using PHP. I’m trying to access the selected value from this dropdown list using JavaScript when the user makes a selection. However, the JavaScript code I’ve written to capture the selected value is not working correctly, and it always returns an empty value.
<form id="form" name="form" method="POST" action="selectDoctor">
<h2 class="heading__4"> Escolher Especialidade:</h2>
<select name="specialty" id="specialtySelect">
<option value=""> Selecione </option>
<?php
foreach ($specialties as $specialty) {
echo '<option id="result" value="' . $specialty['speciality_id'] . '">' . $specialty['speciality_name'] . '</option>';
}
?>
<button class="btn btn-primary mt-3">Seguinte</button>
</form>
<script>
const selectElement = document.getElementById("specialtySelect");
const result = document.getElementById("result");
selectElement.addEventListener("change", (event) => {
console.log(event.target.value);
});
</script>
Console.log(event.target.value) returns empty
2
Answers
You cannot use the same ID on your options.
What you need to do is read the selected index of your
<option>
You also missed the closing
</select>
tag.In your script, you are currently only attempting to read the value once, not on the change event. See the example below.
Working example: https://jsfiddle.net/2zopahtb/
Here are the explanations for each fix: