Creating New Options in a SELECT Control


Creating New Options in a <SELECT> Control

You can change the items in a <SELECT> control on-the-fly . Not only can you change the text property (and therefore the caption) of each item in a <SELECT> control, you also can add or remove items using the add and remove methods . The catch here is that the add and remove methods are methods of the <SELECT> control itself in the Netscape Navigator (see Table 13.11), and of the options collection in the Internet Explorer (see Table 13.15).

Here's an example that shows how to change the items in a <SELECT> control when the user clicks buttons . The <SELECT> control here will display a list of three colors (red, white, and blue) when it first appears, and when you click the Colors button, or four numbers (1, 2, 3, and 4) when you click the Numbers button. To do this, it has to add and remove items as needed, using both the Netscape Navigator 6+ (earlier versions do not support functions like remove and createElement ) and Internet Explorer syntax. Here's what the code looks like:

(Listing 13-11.html on the web site)
 <HTML>      <HEAD>          <TITLE>Changing Select Options</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function colors()   {   document.form1.select1.options[0].text = "Red"   document.form1.select1.options[1].text = "White"   document.form1.select1.options[2].text = "Blue"   if(navigator.appName == "Netscape") {   document.form1.select1.remove(3)   }   if (navigator.appName == "Microsoft Internet Explorer") {   document.form1.select1.options.remove(3)   }   }   function numbers()   {   document.form1.select1.options[0].text = "1"   document.form1.select1.options[1].text = "2"   document.form1.select1.options[2].text = "3"   if(navigator.appName == "Netscape") {   var option1 = document.createElement("OPTION")   document.form1.select1.add(option1, null)   option1.innerHTML = "4"   }   if (navigator.appName == "Microsoft Internet Explorer") {   var option1 = document.createElement("OPTION")   document.form1.select1.options.add(option1)   option1.innerHTML = "4"   }   }  //-->          </SCRIPT>      </HEAD>       <BODY>          <H1>Changing Select Options</H1>          <FORM NAME="form1">  <SELECT NAME="select1">   <OPTION SELECTED>Red   <OPTION>White   <OPTION>Blue   </SELECT>  <INPUT TYPE="BUTTON" VALUE="Colors" onClick="colors()">              <INPUT TYPE="BUTTON" VALUE="Numbers" onClick="numbers()">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 13.12, where I've clicked the Numbers button to make the <SELECT> control display the list of numbers.

Figure 13.12. Changing items in a <SELECT> control on-the-fly.

graphics/13fig12.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net