<option>

The <option> element represents an option in the drop-down box (<select>, <optgroup> or <datalist>). It is an instance of the HTMLOptionElement interface.

Attributes

In addition to inheriting the attributes and methods of the HTMLElement interface, the HTMLOptionElement interface has the following attributes.

-disabled: Boolean value, indicating whether the item is selectable. -defaultSelected: Boolean value, indicating whether the item is selected by default. Once set to true, the value of this item is the default value of <select>. -form: Returns the form element where <option> is located. If it does not belong to any form, null is returned. This attribute is read-only. -index: Integer, indicating the position of the option in the entire drop-down list. This attribute is read-only. -label: A string indicating the description of the option. If this attribute is not set, the text content of the option is returned. -selected: Boolean value, indicating whether the option is selected. -text: String, the text content of the option. -value: string, the value of the option. When the form is submitted, the attribute of the selected item is uploaded.

Option() Constructor

The browser natively provides the Option() constructor to generate HTMLOptionElement instances.

new Option(text, value, defaultSelected, selected);

It accepts four parameters, all of which are optional.

-text: string, which represents the text content of the option. If omitted, an empty string is returned. -value: A string that represents the value of the option. If omitted, the value of the text attribute is returned by default. -defaultSelected: Boolean value, indicating whether the item is selected by default, the default is false. Note that even if it is set to true, it does not mean that the item's selected property is true. -selected: Boolean value, indicating whether the item is selected, the default is false.

var newOption = new Option("hello", "world", true);

newOption.text; // "hello"
newOption.value; // "world"
newOption.defaultSelected; // true
newOption.selected; // false

In the above code, the defaultSelected property of newOption is true, but it is not selected (that is, the selected property is false).