Set Default Value for HTML Select Element



To set the default value for an HTML <select> element, we can use HTML selected attribute. It is used when you want to display a predefined value on your drop down menu.

In this article we are having a dropdown list of four options, our task is to set the default value for an HTML select element.

Steps to Set Default Value for select Element

We will be following below mentioned steps to set the default value for HTML select element:

  • We have created a dropdown list using select tag and then added options to the list using option tag.
  • We have used selected attribute on the option which we want to set the default value of the dropdown list.
  • We have also used disabled and hidden attribute. The disabled attribute prevents the option from being selected and hidden attribute hides the option from dropdown list. This is helful when you want to display an instruction but don't want to include it in option.

Example

Here is a complete example code implementing above mentioned steps to set the default value for an HTML <select> element using selected attribute.

<!DOCTYPE html>
<html>
<body>
    <h3>
        To set the default value for an 
        HTML select element
    </h3>
    <p>
        In this example we have used HTML
        <strong>selected</strong> attribute
        to set the default value for HTML
        select element.
    </p>
    <select name="courses">
        <option value="none" selected disabled hidden>
            Choose any option...
        </option>
        <option value="Java">Java</option>
        <option value="Discrete Mathematics">
            Discrete Mathematics
        </option>
        <option value="Chemistry">Chemistry</option>
        <option value="IOT">IOT</option>
    </select>
</body>
</html>

Conclusion

In this article, we have discussed how to set the default value for an HTML <select> element using selected attribute.

Updated on: 2024-09-20T21:35:42+05:30

608 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements