dynamic options passing
This example dynamically adds and removes options from a select using plain javascript
by Rayudu Ikkurthi
HTML
<select id="couties" onchange="myfunction()">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="dynamic-select">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<button onclick="addOption()">add item</button>
<button onclick="removeOption()">remove item</button>
<button onclick="removeAllOptions()">remove all</button>
JavaScript
function myfunction(){
var slectedValue = document.getElementById("couties").value;
var items = ["vallabha","rayudu"]
alert(slectedValue)
removeAllOptions();
if(slectedValue == 2){
addTwoOption(items);
}
else{
addOption();
}
}
function addOption(){
var select = document.getElementById("dynamic-select");
select.options[select.options.length] = new Option('New Element', '0');
}
function addTwoOption(items){
var select = document.getElementById("dynamic-select");
for(var i = 0; i < items.length; i++){
select.options[select.options.length] = new Option(items[i], i);
}
}
function removeOption(){
var select = document.getElementById("dynamic-select");
select.options[select.options.length - 1] = null;
}
function removeAllOptions(){
var select = document.getElementById("dynamic-select");
select.options.length = 0;
}