Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 466
Austin Lovell Avatar asked Oct 17 '12 16:10

Austin Lovell


2 Answers

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/

like image 139
Thomas Avatar answered Nov 15 '22 04:11

Thomas


I tweaked an example from jquery validate to get this working for you. I know in your original question you asked for it to be based in HTML5 but maybe this blended example is acceptable.

http://jsfiddle.net/36MkJ/

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
    <script>
        $(document).ready(function(){
            $("#carsForm").validate();
        });
    </script>
</head>
<body>
<form class="cmxform" id="carsForm" method="get" action="">
    <select name="cars" class="required">
        <option value="">Select a car</option>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="fiat">Fiat</option>
        <option value="audi">Audi</option>
    </select>
    <p>
        <input class="submit" type="submit" value="Submit"/>
    </p>
</form>

​Original Example was on http://docs.jquery.com/Plugins/Validation

like image 25
zmanc Avatar answered Nov 15 '22 06:11

zmanc