You are here: Reference > JavaScript > client-side > HTML DOM > objects > nodes and tags > select

select object

Browser support:
Creates a drop-down list or list box element.
To add items to the select element, use the option tag.
The select tag allows simple or multiple selection, depending on the state of the multiple property.
  • If multiple selection is allowed, the visual appearance of the select tag can only be a list box.
  • If only one selected element is allowed, the select element may be a drop-down list or a list box. The default appearance is the drop-down list in that case.
You can set the count of the visible rows in a select tag with the size property. If the value of the size property is more than one, the appearance of the select tag is a list box.
The select element is one of the form controls.
The selected state of the control can be submitted to a server if the following conditions are met:
  • A form element must contain the select element.
  • The action property of the container form must be set to the URL of the server.
  • The name property of the select element must be specified and non-empty. If multiple selection is allowed, use brackets [] at the end of the value to reach all of the selected elements on the server side.
In that case:
  • If multiple selection is allowed:
    If there is no selected element in the control, no information is sent with the form belonging to the select tag. Otherwise the name of the select tag is submitted with an array of the selected elements. The array contains the value of the selected option tags.
  • If only one selected element is allowed:
    The name of the select element is submitted with the value of the selected option tag.
If the value property of the option tag is not defined, the text content will be sent. Define different values for the option items, otherwise you cannot identify on the server side which one was selected.
  • If only one selected element is allowed in the select element, the selectedIndex property contains the index of the selected item in the options collection of the select tag. If you need the value of the selected option in a single-selection list, you can use the value property of the select element.
  • If multiple selection is allowed, you can get the selected elements by iterating throw the options collection of the select tag and check the value of the selected property of every option tag.
  • If there is no selected element, the value of the selectedIndex property is -1.
Sometimes it is useful to check the selected options before submitting the form. See Example 4 and 5 for details.

If you need to detect when the selection has changed in a select element, use the onchange event. Example 6 demonstrates it.

Syntax:

Methods that return the object:
document.createElement ("select")
The base interface, through which you can add new functionalities to the select object, is the HTMLSelectElement interface.
If you want to see the HTML objects by categories, please visit this page.
HTML page for this element: select

Possible members:

Properties
Methods
Events
Style properties
accessKey
Sets or retrieves an access key to an element.
align
Sets or retrieves the object's position with respect to the surrounding text.
all
Represents a collection of all elements contained by an element or the entire document.
attributes
Represents a collection of attribute nodes that belong to an element.
baseURI
10
Returns the base URL for the object.
behaviorUrns
Represents a collection of the Uniform Resource Names for all behaviors attached to an element.
canHaveChildren
Retrieves a Boolean value that indicates whether the element can contain child elements.
canHaveHTML
Retrieves a Boolean value that indicates whether the element can contain HTML formatted text.
childElementCount
93.5
Returns the number of element nodes that are direct descendants of the current element.
childNodes
Represents a collection of all nodes that are direct descendants of an element.
children
3.5
Represents a collection of all element nodes that are direct descendants of an element.
className
Sets or retrieves the style class or classes that belong to the element.
clientHeight
Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, but it does not include the scrollBar, border, and the margin.
clientLeft
Returns the width of the left border in pixels.
clientTop
Returns the height of the top border in pixels.
clientWidth
Returns the width of the visible area for an object, in pixels. The value contains the width with the padding, but does not include the scrollBar, border, and the margin.
contentEditable
3
Sets or retrieves whether the contents of the object are editable.
currentStyle
Represents the computed style settings for an element.
dir
Sets or retrieves the text direction as related to the lang property.
disabled
Sets or retrieves the state of an object for user interaction.
filters
Represents a collection of all filter objects applied to an element.
firstChild
Returns a reference to the first child of the current element.
firstElementChild
93.5
Returns a reference to the first child element of the current element.
form
Returns a reference to the form element in which the object is placed.
forms
Represents a collection of all form elements in the current document.
hideFocus
Specifies or returns whether a dotted rectangle (focus rectangle) is drawn around an object while it has focus.
id
Sets or retrieves a unique identifier for the object.
innerHTML
Sets or retrieves the inner HTML content (the source code between the opening and closing tags) of an element.
innerText
Sets or returns the text content of an element including the text content of its descendants.
isContentEditable
Returns a Boolean value that indicates whether the contents of the object are editable by the user.
isDisabled
Returns a Boolean value that indicates whether the object is disabled.
isMultiLine
Returns a Boolean value that indicates whether the contents of an element can be multiline or not.
isTextEdit
Returns a Boolean value that indicates whether the createTextRange method can be used for the element.
lang
Specifies or returns the language of the element.
language
Sets or retrieves the scripting language for the current element. Use it only for the script element.
lastChild
Returns a reference to the last child of the current element.
lastElementChild
93.5
Returns a reference to the last child element of the current element.
length
Returns the number of form controls in a form element or the number of options in a select or keygen element.
localName
9
Returns the local part of the qualified name of the current node.
multiple
Sets or retrieves whether more than one item from a list can be selected.
name
Sets or retrieves the name of a form control that affects the contents of the message submitted to the server.
namespaceURI
93.6
Sets or returns the namespace URI of the current node.
nextElementSibling
93.5
Returns a reference to the next child element of the current element's parent.
nextSibling
Returns a reference to the next child of the current element's parent.
nodeName
Returns the name of the current node.
nodeType
Returns an integer that indicates the type of the node.
nodeValue
Sets or returns the value of the current node.
offsetHeight
Returns the height of the visible area for an object, in pixels. The value contains the height with the padding, scrollBar, and the border, but does not include the margin.
offsetLeft
Returns the left position of an object relative to the left side of its offsetParent element, in pixels.
offsetParent
Returns a reference to the closest ancestor element in the DOM hierarchy from which the position of the current element is calculated.
offsetTop
Returns the top position of the object relative to the top side of its offsetParent element, in pixels.
offsetWidth
Returns the width of the visible area for an object, in pixels. The value contains the width with the padding, scrollBar, and the border, but does not include the margin.
options
Represents a collection of all option elements in a select element.
outerHTML
Sets or retrieves the outer HTML content (the source code including the opening and closing tags) of an element.
outerText
Sets or returns the text content of an element including the text content of its descendants.
ownerDocument
Returns the document object that contains the current node.
parentElement
Returns the parent element of the object in the DOM hierarchy.
parentNode
Returns the parent element of the current node in the DOM hierarchy.
parentTextEdit
Returns the closest ancestor element of the current element in the DOM hierarchy that can be used to create a TextRange object.
previousElementSibling
93.5
Returns a reference to the previous child element of the current element's parent.
previousSibling
Returns a reference to the previous node of the current element's parent.
readyState
Returns a string value that represents the state of the object.
runtimeStyle
Represents the overridden style settings for an element.
scopeName
Retrieves the local name of the namespace declared for the current element.
scrollHeight
Returns the total height of an element's contents, in pixels. The value contains the height with the padding, but does not include the scrollBar, border, and the margin.
scrollTop
Sets or retrieves the number of pixels by which the contents of an object are scrolled upward.
selectedIndex
Specifies or returns the zero-based index of the selected option in a select object or in the selection list of a keygen object.
size
Specifies or returns the count of the visible option items in a selection list. The selection list can be a select element or the selection list of a keygen element.
sourceIndex
Returns the position of the current object in the all collection of the document.
style
Represents the inline style settings for an element or a CSS rule.
tabIndex
Specifies or returns the tabbing order for keyboard navigation using the TAB key.
tagName
Returns the tag name of the current element.
tagUrn
Sets or retrieves the Uniform Resource Name (URN) of the namespace declared for the current element.
textContent
9
Sets or returns the text content of an element including the text content of its descendants.
title
Specifies or returns a tooltip for an element.
type
Returns a string that identifies whether more than one item can be selected in a selection list.
uniqueID
Returns the unique identifier generated by the browser for the object.
unselectable
Sets or retrieves whether the selection process can start in an element's content.
value
Specifies or returns the value of an option or a select element.

Example HTML code 1:

This example illustrates the use of the select element for a single-selection drop-down list:
<form method="post" action="#URL#">
    My favorite fruit:
    <select name="fruit">
        <option value="Apple">Apple</option>
        <option value="Pear">Pear</option>
        <option value="Peach">Peach</option>
    </select>
    <br /><br />
    <input type="submit" value="Send" />
</form>
Did you find this example helpful? yes no

Example HTML code 2:

This example illustrates the use of the select element for a single-selection list box:
<form method="post" action="#URL#">
    My favorite fruit:
    <select name="fruit" size="3">
        <option value="Apple">Apple</option>
        <option value="Pear">Pear</option>
        <option value="Peach">Peach</option>
    </select>
    <br /><br />
    <input type="submit" value="Send" />
</form>
Did you find this example helpful? yes no

Example HTML code 3:

This example illustrates the use of the select element for a multiple-selection list:
<form method="post" action="#URL#">
    My favorite fruits:
    <select name="fruits[]" multiple="multiple">
        <option value="Apple">Apple</option>
        <option value="Pear">Pear</option>
        <option value="Peach">Peach</option>
    </select>
    <br /><br />
    <input type="submit" value="Send" />
</form>
Did you find this example helpful? yes no

Example HTML code 4:

This example checks the selected item in a single-selection list, before submitting the form:
<head>
    <script type="text/javascript">
        function CheckAndSubmit () {
            var fruitForm = document.getElementById ("fruitForm");
            var fruitList = document.getElementById ("fruitList");

            if (fruitList.selectedIndex == 0) {
                alert ("Please select your favorite fruit!");
                return;
            }

            fruitForm.submit ();
        }
    </script>
</head>
<body>
    <form id="fruitForm" method="post" action="#URL#">
        My favorite fruit:
        <select name="fruit" id="fruitList">
            <option value="">Please select a fruit</option>
            <option value="Apple">Apple</option>
            <option value="Pear">Pear</option>
            <option value="Peach">Peach</option>
        </select>
        <br /><br />
        <input type="button" value="Send" onclick="CheckAndSubmit ()" />
    </form>
</body>
Did you find this example helpful? yes no

Example HTML code 5:

This example checks the count of the selected items in a multiple-selection list, before submitting the form:
<head>
    <script type="text/javascript">
        function CheckAndSubmit () {
            var fruitForm = document.getElementById ("fruitForm");
            var fruitList = document.getElementById ("fruitList");

            var selectedCount = 0;
            for (var i = 0; i < fruitList.options.length; i++) {
                if (fruitList.options[i].selected) {
                    selectedCount++;
                }
            }
            if (selectedCount < 2) {
                alert ("Please select at least 2 pieces of fruit!");
                return;
            }

            fruitForm.submit ();
        }
    </script>
</head>
<body>
    <form id="fruitForm" method="post" action="#URL#">
        My favorite fruits:<br />
        <select name="fruits[]" id="fruitList" multiple="multiple">
            <option value="Apple">Apple</option>
            <option value="Pear">Pear</option>
            <option value="Peach">Peach</option>
        </select>
        <br /><br />
        <input type="button" value="Send" onclick="CheckAndSubmit ()" />
    </form>
</body>
Did you find this example helpful? yes no

Example HTML code 6:

This example illustrates the use of the onchange event for a select element:
<head>
    <script type="text/javascript">
        function OnSelectionChange (select) {
            alert ("The selected option is " + select.value);
        }
    </script>
</head>
<body>
    Select an item from the following list:<br />
    <select onchange="OnSelectionChange (this)">
        <option value="Apple" />Apple
        <option value="Pear" />Pear
        <option value="Peach" />Peach
    </select>
</body>
Did you find this example helpful? yes no

Example HTML code 7:

This example displays the text of the selected items in a multiple-selection list:
<head>
    <script type="text/javascript">
        function GetSelected (selectTag) {
            var selIndexes = "";

            for (var i = 0; i < selectTag.options.length; i++) {
                var optionTag = selectTag.options[i];
                if (optionTag.selected) {
                    if (selIndexes.length > 0)
                        selIndexes += ", ";
                    selIndexes += optionTag.text;
                }
            }

            var info = document.getElementById ("info");
            if (selIndexes.length > 0) {
                info.innerHTML = "Selected options: " + selIndexes;
            }
            else {
                info.innerHTML = "There is no selected option";
            }
        }
    </script>
</head>
<body>
    Please select some options (use the CTRL key for multiple selection)
    <br />
    <select multiple="multiple" onchange="GetSelected (this);">
        <option>Apple</option>
        <option>Peach</option>
        <option>Pear</option>
    </select>
    <br /><br />

    <span id="info" style="border:1px solid #606060; background-color:#e0d0e0;"></span>
</body>
Did you find this example helpful? yes no

Example HTML code 8:

This example is similar to the previous one but it displays the value of the selected items in a multiple-selection list:
<head>
    <script type="text/javascript">
        function GetSelected (selectTag) {
            var selIndexes = "";

            for (var i = 0; i < selectTag.options.length; i++) {
                var optionTag = selectTag.options[i];
                if (optionTag.selected) {
                    if (selIndexes.length > 0)
                        selIndexes += ", ";
                    selIndexes += optionTag.value;
                }
            }

            var info = document.getElementById ("info");
            if (selIndexes.length > 0) {
                info.innerHTML = "Selected options: " + selIndexes;
            }
            else {
                info.innerHTML = "There is no selected option";
            }
        }
    </script>
</head>
<body>
    Please select some options (use the CTRL key for multiple selection)
    <br />
    <select multiple="multiple" onchange="GetSelected (this);">
        <option value="Apple">Apple</option>
        <option value="Peach">Peach</option>
        <option value="Pear">Pear</option>
    </select>
    <br /><br />

    <span id="info" style="border:1px solid #606060; background-color:#e0d0e0;"></span>
</body>
Did you find this example helpful? yes no

Example HTML code 9:

This example shows how to create a selection list dynamically:
<head>
    <script type="text/javascript">
        var countries = ['Australia', 'Great Britain', 'Germany', 'United States'];

        function FillCountryList () {
            var countryList = document.getElementById ("country");

            for (var i=0; i < countries.length; i++) {
                    // Option (text, value)
                var countryOption = new Option (countries[i], countries[i]);
                countryList.options.add (countryOption);
            }
        }
    </script>
</head>
<body onload="FillCountryList ()">
    <select id="country">
    </select>
</body>
Did you find this example helpful? yes no

Example HTML code 10:

This example is similar to the previous one, but it uses 2-character alphabetical country codes for option values. It is useful if you want to store the selected country in database.
<head>
    <script type="text/javascript">
        var countries = ['Australia', 'AU', 'Great Britain', 'GB', 'Germany', 'DE', 'United States', 'US'];

        function FillCountryList () {
            var countryList = document.getElementById ("country");

            for (var i=0; i < countries.length; i += 2) {
                    // Option (text, value)
                var countryOption = new Option (countries[i], countries[i+1]);
                countryList.options.add (countryOption);
            }
        }
    </script>
</head>
<body onload="FillCountryList ()">
    <select id="country">
    </select>
</body>
Did you find this example helpful? yes no

Example HTML code 11:

The previous two examples create selection list from arrays. The following one creates a selection list from a string. It is useful if you use AJAX to fill the contents of a selection list. For further details about AJAX, see the page for the XMLHttpRequest object and the responseText property.
<head>
    <script type="text/javascript">
            // the response of an AJAX call (responseText)
        var httpResponse = "Australia,AU,Great Britain,GB,Germany,DE,United States,US";

        var countries = httpResponse.split (",");

        function FillCountryList () {
            var countryList = document.getElementById ("country");

            for (var i=0; i < countries.length; i += 2) {
                    // Option (text, value)
                var countryOption = new Option (countries[i], countries[i+1]);
                countryList.options.add (countryOption);
            }
        }
    </script>
</head>
<body onload="FillCountryList ()">
    <select id="country">
    </select>
</body>
Did you find this example helpful? yes no

Example HTML code 12:

This example illustrates how you can change the items in a select element depending on the selected item in another select element:
<head>
    <script type="text/javascript">
        var countriesAndCities = {};
        countriesAndCities['AU'] = ['Brisbane', 'Melbourne', 'Sydney'];
        countriesAndCities['GB'] = ['Liverpool', 'London', 'Manchester'];
        countriesAndCities['DE'] = ['Berlin', 'Hamburg', 'Munich'];
        countriesAndCities['US'] = ['Chicago', 'Los Angeles', 'New York'];

        function ChangeCityDropList () { 
            
            var countryDropList = document.getElementById ("country");
            var cityDropList = document.getElementById ("city");
            var selCountry = countryDropList.options[countryDropList.selectedIndex].value;

            // remove all cities
            while (cityDropList.options.length) {
                cityDropList.remove (0);
            }

            // add new cities
            var cities = countriesAndCities[selCountry];
            if (cities) {
                for (var i=0; i < cities.length; i++) {
                    var city = new Option (cities[i], i);
                    cityDropList.options.add (city);
                }
            }
        } 
    </script>
</head>
<body onload="ChangeCityDropList ();">   
    <select id="country" onchange="ChangeCityDropList();"> 
        <option value="">-- Country --</option> 
        <option value="AU">Australia</option> 
        <option value="GB">Great Britain</option> 
        <option value="DE" selected="selected">Germany</option> 
        <option value="US">United States</option> 
    </select> 

    <select id="city"> 
    </select> 
</body>
Did you find this example helpful? yes no

Related pages:

External links:

User Contributed Comments

Post Content

Post Content