spacer
Yehuda Shiran July 30, 2000
Adding More Options On Line
Tips: July 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Google Going Native With Chrome
Mozilla Fixes Firefox Flaws as 3.5 Release Nears
Microsoft and Novell Still Bosom Buddies

Sometimes you need to add options to a SELECT element on line. For example, let's take the following element:

<SELECT ID="oSelect">
  <OPTION>List of options to be added
</SELECT>

When you want to add an option, first create a new Option object:

oNewOption = new Option();

Then populate its text property. Let's concatenate a number to the string "Option":

oNewOption.text = "Option " + optionNo;

And finally, let's add the new option to the oSelect object above:

oSelect.add(oNewOption, 0);

The second parameter may take the following values:

  • 0: Add the new option at the top of the list.

  • 1: Add the new option at the end of the list.

  • n: Limit the number of new options to n.

Clicking the button below will add a new option to the list:

Here is the HTML definition of the button and the SELECT box:

<INPUT TYPE="BUTTON" VALUE="Add An Option" onclick="addNewOption()">
<SELECT ID="oSelect">
  <OPTION>List of options to be added
</SELECT>

And here is the script that handles the clicks:

<SCRIPT>
<!--
var optionNo = 0;
function addNewOption() {
  optionNo += 1;
  oNewOption = new Option();
  oNewOption.text = "Option " + optionNo;
  oSelect.add(oNewOption, 1);
}
// -->
</SCRIPT>


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
XML and PHP Simplified · Creating a ASP.NET Contact Form · Data Filtering with PHP
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Intel to Host Live Nehalem Q&A · 12 Tips to Troubleshoot Network File-Sharing · 10 Tips for Selling on Kijiji