Logo

How can I set the default value for an HTML <select> element?

You can set the default (initially selected) option in an HTML <select> element by using the selected attribute on the desired <option>. Here are a few ways to do it:

1. Mark the Desired <option> with selected

<select name="mySelect"> <option value="option1">Option 1</option> <option value="option2" selected>Option 2 (Default)</option> <option value="option3">Option 3</option> </select>
  • How It Works: The <option> marked with selected will appear as the default choice when the page loads.

2. Set the Value Dynamically via JavaScript

If you want to set the default programmatically (e.g., based on certain conditions):

<select id="mySelect"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> <script> document.getElementById('mySelect').value = 'option2'; </script>
  • How It Works: Assigning a value to mySelect.value updates which option is initially selected. This also works after the page has loaded if you need to change the selection later.

Tips

  1. Use selected on Only One Option
    Marking more than one option as selected can cause inconsistent behavior across different browsers.

  2. Validate User Choices
    If using this selection in a form, make sure your server-side logic accepts or validates the default value properly.

  3. Disabled Placeholder
    If you need a prompt, you can simulate a placeholder with a disabled “placeholder” option (as shown below). This option can be the default choice, prompting the user to pick a valid option:

    <select> <option value="" disabled selected hidden>Select an option</option> <option value="1">Option 1</option> <option value="2">Option 2</option> </select>

Level Up Your Web Development Skills

Whether you're building dynamic forms or full-scale web applications, understanding HTML, CSS, and JavaScript fundamentals is essential. If you want to enhance your front-end expertise, check out these courses on DesignGurus.io:

Each course features a pattern-based approach, real-world examples, and hands-on practice to solidify your skills. For more free tutorials and deep-dives on coding best practices, system design, and tech interviews, visit the DesignGurus.io YouTube channel.

CONTRIBUTOR
TechGrind