Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html5

How to set the default value for an HTML `<select>` element

NDUKWE CHIDERA K.

HTML forms are the most commonly used way to collect information from a web page.

The HTML form has different elements such as:

  • Input
  • option
  • label
  • fieldset
  • Optgroup
  • textarea
  • select, and so on.

It also has a host of attributes that can be contained by any of its sub elements.

Examples of such attributes include:

  • target
  • method
  • action
  • autocomplete, and more.

All of these work together to give us the seamless ability to gather data from users of our site.

What is the <select> element in HTML?

This is an element that is used in forms. It prompts the user to choose from a set of options as they wish.

The <select> tag uses the <option> tag to present a set of available choices to the user. The challenge here is that, by default, the tag is displayed on the webpage with the first option.

You will get this by default:

set the default value for <select> element

You can choose your default value by setting your default value of choice to selected, as shown below.

Code


<!DOCTYPE html>
<html>
  
<head>
    <title>
      Setting default of choice in the <select> element
  </title>
</head>
  
<body>
    <select name="plan" id="plan">
  <!-- This is where we set the value to be displayed-->
        <option value="none" selected disabled hidden>
          Select an Option
      </option>
        <option value="free">Free</option>
        <option value="starter">Starter </option>
        <option value="professional">Professional</option>
        <option value="corporate">Corporate</option>
    </select>
</body>
  
</html>

Output

This is the output of the above code:

Note that in the above code, together with selected, we also included hidden and disabled to let us display customized messages which will not be seen as part of the options from which the user can select.

RELATED TAGS

html5
RELATED COURSES

View all Courses

Keep Exploring