A JavaScript listbox is usually an HTML <select> element. A normal select lets the visitor choose one predefined option; adding the multiple attribute allows more than one selection. JavaScript can read the selected value, validate it, enable or disable the control, add or remove options, build dependent lists, and respond to the change event.
<label for="language">Choose a language</label>
<select id="language" name="language">
<option value="">Select one</option>
<option value="PHP">PHP</option>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
</select>
The selected value is available through the element’s value property:
const language = document.getElementById("language");
console.log(language.value);
For the HTML-only foundation, see HTML dropdown list boxes.
Use a <label> connected with for/id, give each option a useful value, and include a blank placeholder when the form requires an explicit choice.
const list = document.getElementById("language");
list.addEventListener("change", () => {
console.log(list.value);
});
| Property / API | Use |
|---|---|
select.value | Value of the first selected option. |
select.selectedIndex | Index of the selected option, or -1 when no option is selected. |
select.options | Live collection of all options. |
select.selectedOptions | Collection of selected options; especially useful with multiple. |
select.disabled | Enable or disable the complete list. |
option.selected | Read or change one option’s selected state. |
new Option(text, value) | Create an option in JavaScript. |
Validate a listbox before form submission, enable or disable a listbox, or respond to the user with the change event.
Use multiple when more than one option is valid. Read the choices from selectedOptions and convert the collection to an array when you want array methods.
const selectedValues = Array.from(list.selectedOptions, option => option.value);
See reading multiple selections and limiting the number of selections.
The original listbox series also covers adding options, removing options, moving options between lists, and copying listbox data with other form fields.
Dependent dropdowns change the second list from the first selection. The related database-backed dropdown tutorial shows how table data can supply those options, while dropdown redirection uses a selected value to choose a destination.
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.
| srinivas | 29-03-2010 |
| It is very good site for learners, who wants work with the php,asp etc.., can u provide more content to learners | |