View video tutorial

HTML selected Attribute

HTML

The HTML selected attribute is a Boolean attribute used on the <option> element to specify whether an option should be the default pre-selected choice when the page loads.

Definition and Usage


➔ The browser will display this option at the top of the dropdown list.

➔ If the selected attribute is not specified, the first

➔ For a boolean attribute like selected , the presence of the attribute (regardless of the value assigned) will select the option.

Syntax
//In HTML
<select id="sample" name="fruit">
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="orange" selected>Orange</option>
</select>
//OR
<option value="value" selected="selected">Option Text</option>

//In Javascript
const element = document.getElementById('sample');
//Using .value
element .value = "banana"; // Changes the selection to 'banana'
// Using .selectedIndex, index starts at 0;
element .selectedIndex = 1; // Changes the selection to second item.

//OR
const orange = document.querySelector('option[value="orange"]');
// Set the 'selected' attribute. Any value will work, even if an empty string.
orange.setAttribute('selected', 'selected');

Applies to

This attribute can be used on the following element.

Attribute Element
selected <option>

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML selected attribute example</title>
</head>
<body>
    <h3>HTML selected attribute example</h3>
    <p>The selected attribute is used to specify whether an option is pre-selected when the page loads.</p>
    <label for="sample">Choose a fruit:</label>
    <select id="sample" name="fruit">
        <option value="apple">Apple</option>
        <option value="banana" selected>Banana</option>
        <option value="orange">Orange</option>
    </select>
</body>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.