Search code examples
htmlrequiredfieldvalidatorrequired

Requiring to make a selection from a drop down html 5


Is it possible to force/require a user to make a selection from a drop down menu? Example:

<form action="">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>

By default "Volvo" is selected. What I want is for the browser to know that the user has made a selection and not accept the auto default.

I am thinking something like this:

<form action="">
<select name="cars" required="required">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>

Any advice?


Solution

  • A lot of time has passed since the question was posted. For anybody stumbling over this like I did, the solution became a lot simpler by now: You can just add a first option to the selection, with no value set. The browser will automatically treat this like "nothing was selected":

    <!DOCTYPE html>
    <html>
      <body>
        <form>
          <select required>
            <option value="">Please select</option>
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="opel">Opel</option>
            <option value="audi">Audi</option>
          </select>
          <input type="submit"/>
        </form>
      </body>
    </html>
    

    JSFiddle showing it work with no further JS required: https://jsfiddle.net/nrs5a7qh/