Select add() Method - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Select

Description

The add() method is used to add an option to a drop-down list.

Syntax

select.add(option,index);

Parameter Values

Parameter Description
optionRequired. Specifies the option to add. Must be an option or optgroup element
index Optional. index position. Index starts at 0. Default to the end of the list

Return Value:

No return value

The following code shows how to Add a "Kiwi" option at the end of a drop-down list:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<form>
  <select id="mySelect" size="8">
    <option>Apple</option>
    <option>Pear</option>
    <option>Banana</option>
    <option>Orange</option>
  </select>
</form>/*from w w w .j a va2s  .com*/
<br>

<button type="button" onclick="myFunction()">Insert option before selected</button>

<script>
function myFunction() {
    var x = document.getElementById("mySelect");
    if (x.selectedIndex >= 0) {
        var option = document.createElement("option");
        option.text = "Kiwi";
        var sel = x.options[x.selectedIndex];
        x.add(option, sel);
    }
}
</script>

</body>
</html>

Related Tutorials