HTML - selected Attribute



HTML selected attribute is used to mark a default option from the select list as already being selected when the page loads.

The default or preferred option in a list of options is highlighted by this feature, which makes user interactions simpler.It was used by web developers to improve user experience and make it simpler for users to explore and make decisions on web forms and interfaces by instantly identifying the default selection inside a dropdown.

Syntax

<option selected></option>

Applies on

Below-listed element allows the use of the HTML selected attribute.

Element Description
<option> HTML <option> tag is used to define the item of the data list for autocomplete, specified by the <datalist> tag, or the items of a drop-down list, defined by the <select> tag.

Examples of HTML selected attribute

Below examples will illustrate the HTML selected attribute, where and how we should use this attribute!

Set an option as already selected in the list

Upon execution, the mother tongue is set by default as hindi.

<!DOCTYPE html>
<html>

<head>
    <title>HTML 'selected' attribute</title>
</head>

<body>
    <h3>Example of the HTML 'selected' attribute</h3>
    <p>Choose your mother tongue:</p>
    <select>
        <option value="">--Choose your option--</option>
        <option value="" selected>Hindi</option>
        <option value="">Tamil</option>
        <option value="">Telugu</option>
    </select>
</body>

</html>

Using selected attribute in functioning a button

When the below code gets executed, 'HTML' is selected by default. On clicking the "Set selected" button, the option gets updated to 'Angular'.

<!DOCTYPE html>
<html>

<head>
    <title>HTML 'selected' attribute</title>
</head>

<body>
    <h3>Example of the HTML 'selected' attribute</h3>
    <p>Select any frontend technology that you know:</p>
    <select>
        <option value="">--Choose your option--</option>
        <option value="" id='html' selected>HTML</option>
        <option value="" id='css'>CSS</option>
        <option value="" id='javascript'>JavaScript</option>
        <option value="" id='angular'>Angular</option>
        <option value="" id='react'>React</option>
    </select>
    <button onclick="Add()">Set selected</button>
    <script>
        function Add() {
         document.getElementById('angular').selected = true;
        }
    </script>
</body>

</html>

Supported Browsers

Attribute Chrome Edge Firefox Safari Opera
selected Yes Yes Yes Yes Yes
html_attributes_reference.htm
Advertisements