сряда, 8 август 2007 г.

JavaScript: Create and Delete Options from a Select Box

This is an option box:
<form name="testform">
<select name="testselect">
<option value="first">first option</option>
<option value="second">second option</option>
<option value="third">third option</option>
<option>your browser can't handle this script</option>
To access options in a select box, you use the following code:


where i is the number of the option you want to access. Remember that the first option is options[0], the second one is options[1] etc.

Now if you want to delete the option, do

document.forms['testform'].testselect.options[i] = null;

By making it null, the option is completely removed from the list. Note that this also affects the numbering of the options. Suppose you remove option[1] from the example above, the old option[2] ('Third option') becomes option[1] etc.

To create a new option, do:

document.forms['testform'].testselect.options[i] = new Option('new text','new value');

where new text is the text the user sees and new value is the VALUE of the new option, the bit that's sent to the server when the form is submitted. Of course the new option overwrites the old one.

To completely clear a select box, do

document.forms['testform'].testselect.options.length = 0;

Няма коментари: