The change event runs after the user commits a new selection in a dropdown list. Use it to read the selected value and update the page without putting JavaScript directly in the HTML onchange attribute.
const month = document.getElementById("s1");
const output = document.getElementById("msg3");
month.addEventListener("change", () => {
output.textContent = month.value;
});
Demo of listbox change event
The original tutorial used an inline onChange handler. addEventListener() keeps behavior in JavaScript and allows more than one listener.
<select id="s1" name="month">
<option value="Jan">January</option>
<option value="Feb">February</option>
<option value="Mar">March</option>
</select>
<div id="msg3" aria-live="polite"></div>
const value = month.value;
const text = month.options[month.selectedIndex].text;
The value is the data assigned to the option. The text is what the visitor sees.
selectedIndex returns the position of the selected option. Prefer stable option values for application logic because indexes change when options are inserted or reordered.
A multiple-select needs a different approach because several options may be selected. Continue with multiple listbox selection.
getElementById() · add options · listbox reference · JavaScript validation
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.