1

Even if there's no text in the field, it still directs to the email page.

First check whether anything has been entered in the required field. If there's no text in the textfield it should display an alert.

<html>
 <head>
  <script type="text/javascript">
    function checkForm(){        
     if (document.getElementById("lname").value == ""){          window.alert("Please enter your last name");
       document.getElementById("lname").focus();
       return false;
      }
      return true;
     }
            
  </script>
  <title>Testing your Javascript skills</title>
 </head>
 <body>
   <form action="mailto:me@fakeemail.com" onsubmit="checkForm()">
           
           <p>The fields marked with an asterisk (*) are required fields:</p>
           
           <p>*First Name: <input type="text" name="fname" id="fname" /></p>
           <p>*Last Name: <input type="text" name="lname" id="lname" /></p>
          
           <input type="submit" value="Enter Info" />
          </form>
          
 </body>
</html
    
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Lyn
  • 11
  • 1

1 Answers1

1

Pass the event object on submit handler and if last name is empty prevent the default behavior

function checkForm(e) {
  if (document.getElementById("lname").value === "") {
    e.preventDefault();
    window.alert("Please enter your last name");
    document.getElementById("lname").focus();
    return false;
  }
  return true;
}
<form action="mailto:me@fakeemail.com" onsubmit="checkForm(event)">
  <p>The fields marked with an asterisk (*) are required fields:</p>
  <p>*First Name: <input type="text" name="fname" id="fname" /></p>
  <p>*Last Name: <input type="text" name="lname" id="lname" /></p>
  <input type="submit" value="Enter Info" />
</form>
brk
  • 48,835
  • 10
  • 56
  • 78