1. Computing & Technology

JavaScript By Example

DOM Form: 9. Add An Option To A Select

From , former About.com Guide

One of the main uses for JavaScript when it was first developed was to interact with forms. This meant that right from the start JavaScript provided a number of built in objects specifically intended for use in interacting with forms. Most of these objects are seldom ever used any more as the Document Object Model introduced a more standard way of interacting with the form fields in the same way that JavaScript can now interact with the the rest of the page content.

There are still a few instances where these form field objects provide a simpler way of performing form processing. One of these is where you want to dynamically add a new option to the end of a select list. Instead of creating a new option node, adding a value and text and then adding the node to the select we can make use of the Option object to create the node for us with the value and text already attached as this example demonstrates.


addOption = function(id, val, txt) {
var selbox;
selbox = document.getElementById(id);
selbox.options[selbox.options.length] = new Option(txt, val);
}

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example

©2012 About.com. All rights reserved.

A part of The New York Times Company.