Javascript DOM HTML Select add() Method

Introduction

Add a "Kiwi" option at the end of a drop-down list:

Click the button to add a "Kiwi" option at the end of the dropdown list.

View 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>//  w  ww.jav  a2s .  com
<br>
<button type="button" onclick="myFunction()">Insert option</button>

<script>
function myFunction() {
  var x = document.getElementById("mySelect");
  var option = document.createElement("option");
  option.text = "new value";
  x.add(option);
}
</script>

</body>
</html>

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

Parameter Values

Parameter Description
optionRequired. Specifies the option to add. Must be an option or optgroup element
index Optional. Set the index position to insert. Index starts at 0.

If no index is specified, the new option will be inserted at the end of the list.




PreviousNext

Related