Requiring a Form Field

From JustHumans

Jump to: navigation, search

You can require a field via JavaScript because JustHumans respects the "onSubmit" setting in the form tag. A good example of this is the JustHumans contact page:

http://www.justhumans.com/jh/contact

View source on that page to see how it works.

The form code looks like this:

  <form onSubmit="return( isFormComplete( this ) )">
  <input type="hidden" name="sort" value="order:name,email,url,comments">
  <tr>
   <td align="right">Name:</td><td><input type="text" name="name"></td>
  </tr>
  <tr>
   <td align="right">Email:</td><td><input type="text" name="email"> (optional)</td>
  </tr>
  <tr>
   <td align="right">URL:</td><td><input type="text" name="url"> (if applicable)</td>
  </tr>
  <tr>
   <td>Comments:</td>
  </tr>
  <tr>
   <td colspan="2"><textarea name="comments" rows="10" cols="60"></textarea></td>
  </tr>
  <tr>
   <td colspan="2"><script language="JavaScript" src="http://verify.justhumans.com/verification.js?k=6b91e0ee949213531673d187d7dc93&t=1"></script></td>
  </tr>
  </form>

Notice that the fields "name" and "comments" are required while the others are not. So we need some JavaScript that requires those two fields. The <form> tag requires the function "isFormComplete" which checks this. The idea is if the script returns "false", the form will not submit.

<script language="JavaScript">
<!--

function isFormComplete( form ) {
  if ( form.name.value == "" ) {
    form.name.focus( );
    alert( "Please enter your name." );
    return( false );

  }
  else if ( form.comments.value == "" ) {
    form.comments.focus( );
    alert( "Please enter a comment." );
    return( false );

  }
  return true;

}

// -->
</script>

So if the name field is blank, we focus on the name field and show an alert. If something is set in the name field, we go on to do the same with the comments field. If that looks OK as well, we return true which allows the form to be submitted.

Note: Only set onSubmit in the form if you actually are going to use it. A blank onSubmit setting will cause your form not to submit with JustHumans.

Personal tools