Javascript Reference - HTML DOM Select Object








The Select object represents an HTML <select> element.

Select Object Collections

Collection Description
options Get a list of all the options in a drop-down list

Select Object Properties

Property Description
disabled Disable or enable the drop-down list
form Get the form that contains the drop-down list
length Get the number of <option> elements in a drop-down list
multiple Sets or gets if the drop-down list supports multiple selection
name Sets or gets the name attribute of a drop-down list
selectedIndex Sets or gets the index of the selected option in a drop-down list
size Sets or gets the size of a drop-down list
type Returns the type of a drop-down list
value Sets or gets the value of the selected option in a drop-down list




Select Object Methods

Method Description
add() Adds an option to a drop-down list
remove() Removes an option from a drop-down list

Standard Properties and Events

The Select object supports the standard properties and events.

Example

We can access a <select> element by using getElementById().


<!DOCTYPE html>
<html>
<body>
<!-- w ww.  java 2 s  .c  o  m-->
<select id="mySelect" size="4">
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
</select>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
    var x = document.getElementById("mySelect").length;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

We can create a <select> element by using the document.createElement() method.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from w w w.j a  v a  2 s . c  o  m-->
    var x = document.createElement("SELECT");
    x.setAttribute("id", "mySelect");
    document.body.appendChild(x);

    var z = document.createElement("option");
    z.setAttribute("value", "A");
    var t = document.createTextNode("A");
    z.appendChild(t);
    document.getElementById("mySelect").appendChild(z);
}
</script>

</body>
</html>

The code above is rendered as follows: