Dynamically Add/Remove Options From Select JavaScript
This tutorial shows how to get, add and remove options form a select/dropdown using plain JavaScript. We demonstrate this with the following example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamically add/remove options select - JavaScript</title>
</head>
<body>
<select id="dynamic-select">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<button onclick="getOption()">get item</button>
<button onclick="addOption()">add item</button>
<button onclick="removeOption()">remove item</button>
<button onclick="removeAllOptions()">remove all</button>
<script src="script.js"></script>
</body>
</html>
The script.js
is located in the same directory as the html page.
function getOption(){
var select = document.getElementById("dynamic-select");
if(select.options.length > 0) {
var option = select.options[select.selectedIndex];
alert("Text: " + option.text + "\nValue: " + option.value);
} else {
window.alert("Select box is empty");
}
}
function addOption(){
var select = document.getElementById("dynamic-select");
select.options[select.options.length] = new Option('New Element', '0', false, false);
}
function removeOption(){
var select = document.getElementById("dynamic-select");
select.options[select.selectedIndex] = null;
}
function removeAllOptions(){
var select = document.getElementById("dynamic-select");
select.options.length = 0;
}
Demo
Download
Download it – dynamically-add-remove-options-select-javascript-example
thx, simple and easy