Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating new select list options dynamically

dynamic listboxes !

Creating new select list options dynamically

by  simonchristieis  Posted    (Edited  )
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)
}
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top