JavaScript Options
Learn how to dynamically change select options with JavaScript. Explore practical implementations with interactive examples.
Changing Options Dynamically
This example demonstrates how to change selection options dynamically using JavaScript. The SIZE
attribute of the SELECT
tag creates a list box with the number of items specified. Without the SIZE attribute, you get a dropdown box instead.
- Accessing form elements through JavaScript
- Modifying option text dynamically
- Handling button click events
- Resetting form elements to original state
function changeOptions(form) { // Change the text of each option form.list.options[0].text = "Choice1"; form.list.options[1].text = "Choice2"; form.list.options[2].text = "Choice3"; } function resetOptions(form) { // Reset options to original text form.list.options[0].text = "item 1"; form.list.options[1].text = "item 2"; form.list.options[2].text = "item 3"; }
Dynamic Options Live Demo
Example 1: Adding and Removing Options
This example demonstrates how to dynamically add and remove options from a select element. We'll use the add()
and remove()
methods to manipulate the options collection.
function addOption() { const select = document.getElementById('addRemoveSelect'); const newOption = new Option("New Option " + (select.options.length + 1), "value" + (select.options.length + 1)); select.add(newOption); } function removeOption() { const select = document.getElementById('addRemoveSelect'); if (select.selectedIndex !== -1) { select.remove(select.selectedIndex); } else { alert("Please select an option to remove"); } }
Add/Remove Options Live Demo
Example 2: Changing Multiple Select Options
This example shows how to dynamically change options in a multi-select element based on another selection. We'll populate the second select based on the category selected in the first.
const categories = { fruits: ["Apple", "Banana", "Orange", "Mango"], vegetables: ["Carrot", "Broccoli", "Spinach", "Potato"], drinks: ["Water", "Juice", "Soda", "Tea"] }; function updateItems() { const categorySelect = document.getElementById('categorySelect'); const itemSelect = document.getElementById('itemSelect'); const selectedCategory = categorySelect.value; // Clear current items itemSelect.innerHTML = ''; // Add new items based on category categories[selectedCategory].forEach(item => { const option = new Option(item, item.toLowerCase()); itemSelect.add(option); }); }
Dynamic Multi-Select Live Demo
More Examples
Explore more JavaScript examples to enhance your learning experience: