Sunday, 17 February 2013

Contact form – required fields check with JavaScript

Below is a simple JavaScript to add to your contact form when you need to check if the required fields are empty. The script will not only check but will focus required/empty field.

The form:

<style>
#form fieldset.normal label{width: 10em;display:block; float:left;}
</style>
<form id="form" action="" method="post" name="form" onsubmit="return validateForm(form);"
  <fieldset class="normal">
    <label for="FirstName">First Name *</label><input type="text" name="FirstName" size="40" /><br/>
    <label for="LastName">Last Name *</label><input type="text" name="LastName" size="40" /><br/>
    <label for="EmailAddress">Email Address *</label><input type="text" name="EmailAddress" size="40" /><br/>
        <label for="Message">Message *</label><textarea cols="40" name="Message" rows="10"></textarea><br/>
  </fieldset>
<input type="submit" value="submit" />

The script:

<script type="text/javascript" language="javascript">
function validateForm(thisform){
 if(thisform.FirstName.value=="") {
   alert("Please enter your First Name.");
   thisform.FirstName.focus();
   return false;
 }
 if(thisform.LastName.value=="") {
   alert("Please enter your Last Name.");
   thisform.LastName.focus();
   return false;
 }
 if(thisform.EmailAddress.value=="") {
   alert("Please enter your Email Address.");
   thisform.EmailAddress.focus();
   return false;
 }
if(thisform.Message.value=="") {
   alert("Please enter your Message.");
   thisform.Message.focus();
   return false;
 }
}</script>

And here is the script in action doing the checks in the form:






Thanks to Stuart McMath for cleaning up and enhancing the script code.

No comments:

Post a Comment