Adding options to a select element in html using dynamic javascript
var optn = new Option();
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
We can add new options to a select element using the options array present in the select object. We can create a new option using the new operator and Option class provided by javascript or by using document.createElement(“OPTION”);
Removing all options from a select box
if(selectbox && selectbox.options && selectbox.options.length > 0){
while(selectbox.options.length > 0){
selectbox.remove(0);
}
}
}
To remove a option from select element we can use the remove method in the select object. It takes the index of the option to be removed as an argument.
Here is a sample html snippet which uses select element and addition and removal of options using javascript
<body>
Select Box 1: <select id=”selectbox1″></select>
<br />
<input type=”button” onclick=”clearSelectBox(‘selectbox1’)” value=”Remove” />
<input type=”button” onclick=”addItems(‘selectbox1’)” value=”Add” />
</body>
<script>
function removeAllOptions(selectbox){
if(selectbox && selectbox.options && selectbox.options.length > 0){
while(selectbox.options.length > 0){
function addOption(selectbox, value, text){
var optn = new Option();
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
function clearSelectBox(selectBoxId){
var selectbox = document.getElementById(selectBoxId);
removeAllOptions(selectbox);
}
function addItems(selectBoxId){
var selectbox = document.getElementById(selectBoxId);
addOption(selectbox, 1, ‘One’);
addOption(selectbox, 2, ‘Two’);
addOption(selectbox, 3, ‘Three’);
addOption(selectbox, 4, ‘Four’);
addOption(selectbox, 5, ‘Five’);
addOption(selectbox, 6, ‘Six’);
}
window.onload = addItems(‘selectbox1’)
</script>
</html>