
HTML Selected Attribute
The selected attribute is used in HTML to pre-select an option within a <select> element, indicating that it should be the default selected option when the page loads or the <select> element is rendered.
Here’s an example of how to use the selected attribute in HTML:
<select>
<option value="option1">Option 1</option>
<option value="option2" selected>Option 2</option>
<option value="option3">Option 3</option>
</select>In the above example, the <select> element contains multiple <option> elements. The option with the selected attribute set will be initially displayed as the selected option when the page loads. In this case, “Option 2” will be pre-selected.
You can use JavaScript to dynamically set the selected attribute based on user actions or other conditions. Here’s an example:
<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<script>
// JavaScript code to set the selected option dynamically
var selectElement = document.getElementById("mySelect");
selectElement.value = "option3";
// The option with value "option3" will be selected
</script>In the above example, JavaScript is used to set the value of the <select> element to “option3”. As a result, the corresponding <option> element with the value “option3” will be selected.
The selected attribute can be combined with JavaScript to handle dynamic selection, or it can be set directly in the HTML markup to specify the default selected option.