SoFunction
Updated on 2025-02-28

JavaScript options attribute collection operation code

Copy the codeThe code is as follows:

<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>
</select>
</form>

Use the following code to access the options in the drop-down box:
Copy the codeThe code is as follows:

// Get the option object
['testform'].[i]

If you want to delete the option
Copy the codeThe code is as follows:

['testform'].[i] = null;

If you flag this option object as null, this option will be completely deleted from the list.
Note: This operation will affect the number of options. Suppose in the above example, you delete option[1], and the original option[2] element ('Third option') will become option[1] element (option elements are topped in order).
Create a new option, as follows:
Copy the codeThe code is as follows:

['testform'].[i] = new Option('new text','new value');

The user sees the text and value displayed by the option on the page are the VALUE attributes of this option.
When the form is submitted, the VALUE value is passed to the WEB server.
If you want to clear all options in the select box, the following is:
Copy the codeThe code is as follows:

['testform']. = 0;