O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Changing select Element Content

NN 4, IE 4

Problem

You want to change the options in a select element in response to other form control settings.

Solution

Begin by removing all option elements from the desired select element:

document.myForm.mySelect.options.length = 0;

Then repopulate the option elements with new option objects:

document.myForm.mySelect.options[0] = new Option("Extra Fine", "xf", false, false);
document.myForm.mySelect.options[1] = new Option("Fine", "f", false, false);
document.myForm.mySelect.options[2] = new Option("Medium", "m", false, false);

This syntax works for all browsers from IE 4 and NN 4 onward, but Navigator 4 does not resize the width of the select element to fit new, wider option text, and generally requires a call to history.go(0) to force the revised options to appear.

Discussion

The constructor function syntax for the option object is as follows:

var newOpt = new Option("text", "value", isDefaultSelectedFlag, isSelectedFlag);

The text parameter is a string containing the item's label as seen by the user in the select list, while the value parameter is the otherwise hidden string that is submitted with the form if the option is selected. The two Boolean parameters let you set whether the option is the default selected option (i.e., the equivalent of having the selected attribute set in the HTML for the option element), and whether the option is currently selected.

You can replace individual options by assigning a new option object to one of the elements ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required