Required Drop Down Box in Javascript

I have a form which contains a drop down box. I want it to be a required field, and I want the three options to be weighed as easily as possible (so I don’t want one selected at the beginning).

So far, this is my drop down menu:-

  • ------------ Please Select ------------
  • Option 1
  • Option 2
  • Option 3

Is there a javascript function (preferably) so that if “Please Select” is submitted, then the form throws up an error alert saying that it needs to be something else?

Thanks for any help :slight_smile:

You can check when the onsubmit event is thrown by checking either the value (set it to -1) or by checking the selectedIndex.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Untitled Document</title>
        <link rel="stylesheet" type="text/css" media="screen" />
        <style type="text/css"></style>
        <script type="text/javascript">
            function validateDropDown() {
                var ddl = document.getElementById('ddl');
                if(ddl.selectedIndex == 0 || ddl.options[ddl.selectedIndex].value == -1) {
                    alert('select another option!');
                    return false;
                }
                return true;
            }
        </script>
    </head>
    <body>
       
        <form onsubmit="return validateDropDown('ddl');">
            <select id="ddl">
                <option value="-1">------------ Please Select ------------</option>
                <option>Option 1</option>
                <option>Option 2</option>
                <option>Option 3</option>
            </select>
            <input type="submit" />
        </form>
 
    </body>
</html>