Current course:

Form Validation

It is common that you may want to validate that the information in the form is correct.



If you do not enter any information it will alert you.

Example:

<head>
      <script type="text/javascript">
            function notEmpty() {
                  var myTextField = document.getElementById('theText');
                  if (myTextField.value != "") {
                        alert("You entered: " + myTextField.value);
                  } else {
                        alert("Would you please enter some text?");
                  }
            </script>
</head>
<body>
      <p><input type='text' id='theText' />
      <input type='button' onclick='notEmpty()' value='Form Checker' /></p>
</body>




To check to see if they did not select a choice from a pulldown menu:
Pick a color:

Check dropdown

<head>
      <script type="text/javascript">
            function checkDropdown(choice) {
                  var selectBox = document.getElementById(choice);
                  var selected = selectBox.selectedIndex;
                  var selectedValue = selectBox.options[selected].value;
                  if (selected == 0) {
                        alert("You didn't choose an option from the drop-down list.");
                  } else {
                        alert("You chose " + selectedValue + ". Good choice!");
                  }
            }
      </script>
</head>
<body>
      <form>
            <select id="myselect">
                  <option value="" selected></option>
                  <option ="red">red</option>
                  <option ="blue">blue</option>
                  <option ="green">green</option>
                  <option ="yellow">yellow</option>
                  <option ="purple">purple</option>
            </select>
            <a href="javascript: checkDropdown('myselect');">Check dropdown</a>
      </form>
</body>