Library code snippets

Dynamically Adding OPTIONS to SELECT

Illustrates how to add OPTIONS to a SELECT using client-side JavaScript


Feel the need to add to the options that are available in a <SELECT> tag from the browser? The code below contains an illustration of the basic technique.

Dim anOption
Set anOption = document.createElement("OPTION")
document.form1.select1.options.add anOption
anOption.innerText = "Two"
anOption.Value = "2"


 Want to do the same thing, but in JavaScript. Try the following    

var anOption = document.createElement("OPTION")
document.form1.select1.options.add(anOption)
anOption.innerText = "Two"
anOption.Value = "2"


Almost too easy, isn't it.    
 

Comments

  1. 20 Jul 2007 at 17:18
    In order for this to work in both FF and IE it needs to be .innerHTML (instead of .innerText).
    Oh and classic VB developers have to watch out for case sensitive javascript...
    it need to be .value (instead of .Value)



  2. 16 May 2006 at 22:07
    I tried this using IE, and a get an error saying "invalid argument".

  3. 26 Aug 2005 at 17:03

    Hi!


    Great simple code for adding Options to a SELECT.


    Is it possible to create the SELECT element as well?


    I need to add rows dynamycally to a table, and in one TD of each row there should appear a SELECT.


    Thanks!

  4. 01 Jan 1999 at 00:00

    This thread is for discussions of Dynamically Adding OPTIONS to SELECT.

Leave a comment

Sign in or Join us (it's free).

Bruce Johnson I am the owner of a small application development consulting company that specialized in the design and implementation of Internet-based applications. While there are others who can make a web site...

Related podcasts

  • jQuery in ASP.NET

    In this episode Chris Brandsma, Rick Strahl, Dave Ward, Bertrand Le Roy, Scott Koon, and Steven Harman discuss Microsoft's jQuery in ASP.NET announcement.This episode of the Alt.NET Podcast is brought to you by LLBLGen Pro, the most mature O/R mapper and code generator out there.Are you loo...

Events coming up

  • Feb 25

    Mitcho's talk on Ubiquity and/or JetPack

    Cambridge, United States

    Our February 2010 JavaScript Meetup will be held on Thursday, February 25th at Microsoft Research Center located at One Memorial Drive in Cambridge. When you arrive security will direct you to the correct floor. There is also parking available at a cheap evening rate in the building. Parking is also free on the street in front of the building at 6 PM.At 6:30 PM our fellow member Mitcho (mitcho.com) will share his knowledge of Ubiquity and/or JetPack. I hear he is an awesome presenter.

Want to stay in touch with what's going on? Follow us on twitter!