I have seen several posts recently on the subject of creating drop down lists dynamically.
So I thought I'd write a small FAQ.
Here's how to delete the options of an existing select element.
When I create select boxes I always display a message in the first option ("** Select **"), so when I'm deleting options I leave this one alone, if you want to delete all options then change this line:
while(objSelect.options.length > 1)
to
while(objSelect.options.length > 0)
f = form name
e = select name
[color #ff0000]
Code:
function clearSelect(f,e){
var objSelect=document.forms[f].elements[e];
while(objSelect.options.length > 1){objSelect.remove(1);}
return objSelect;
}
[/color]
This is how we can create a new element.
[color #ff0000]
Code:
function createOption(f,e,newValue,newText){
var objSelect=document.forms[f].elements[e];
var objOption = document.createElement("option");
objOption.text = newText
objOption.value = newValue
if(document.all && !window.opera)
{objSelect.add(objOption);}
else
{objSelect.add(objOption, null);};
}
[/color]
So there are your basic functions to create a dynamic select object.
Moving on from this if you want to create dynamic optgroups, use
Thanks to mwolf00 for the following:
function create(){
optGroup = document.createElement('optgroup')
var objSelect=document.forms(0).elements(0);
var objOption=document.createElement("option")
objOption.innerHTML = "tset"
objOption.value = "simon"
optGroup.label = "simple"
objSelect.appendChild(optGroup)
optGroup.appendChild(objOption)
}