Handling select items

Adding item

opts[46] = new Option("Option text", "Option value");

Unlike Java, JavaScript arrays automatically expand. See JavaScript Array.

Removing item

opts[46] = null;

Unlike Java, JavaScript arrays automatically shrink. See JavaScript Array.

Removing all items

opts.length = 0;

The following is an example of dynamically creating submenus in the second selection box when selecting a main menu in the first selection box.

<!DOCTYPE html>
<meta charset="UTF-8" />
<title>Handling select items</title>
<script type="text/javascript">
function chooseLang() {
  var form = document.getElementById("testForm");
  var lang = form.programLanguage.value;

  switch (lang) {
  case "java":
    form.step.options[0] = new Option("Java Introduction","javaIntro");
    form.step.options[1] = new Option("Class and Object","ClassObject");
    form.step.options[2] = new Option("Java DataType","JavadataType");
  case "javascript":
    form.step.options[0] = new Option("JavaScript Introduction","javascriptIntro");
    form.step.options[1] = new Option("JavaScript DataType","JavascriptDataType");
    form.step.options[2] = new Option("JavaScript Objects","JavascriptObjects");
    form.step.options.length = 0;
<form id="testForm" action="sel.html">
  <select name="programLanguage" onchange="chooseLang()">
    <option value="">--Select Language</option>
    <option value="java">Java</option>
    <option value="javascript">JavaScript</option>
  <select name="step">
  <input type="submit" value="Test" />

Selecting the top level in the language selection initializes the second selection box.

Run example