Friday, November 4, 2011

Customizing JQuery Error Messages

Ok so I went on a wild goose chase to find out how to customize jQuery messages AND place them in a nicer area on the page than the default which is somewhere that doesn't look good.

I had to dig around in Google land but finally pieced together a solution:

Here is my jQuery code snippet:


$(document).ready(function(){
$("#step1").validate({
rules: {
institutionName: "required",
institutionAddress: "required",
institutionCity: "required",
institutionState: "required",
institutionPostalCode: "required",
institutionCountry: "required",
institutionLanguage: "required"
},
messages: {
institutionName: "Please enter the name of your institution",
institutionAddress: "Please enter your institution's address",
institutionCity: "Please enter your institution's city",
institutionState: "You must select a state",
institutionPostalCode: "Please enter your institution's postal code",
institutionCountry: "Please select a country",
institutionLanguage: "Please select a preferred language"
},
// the errorPlacement has to take the table layout into account
errorPlacement: function(error, element) {
if ( element.is(":radio") )
error.appendTo( element.parent().next() );
else if ( element.is(":checkbox") )
error.appendTo( element.parent().next() );
else
error.appendTo( element.parent().next() );
},

});

});


Now let's explain:

1. In the code snippet above, step1 is the NAME of my form.

2. In the RULES piece of the code, these are all of the fields that I would like to be required.

3. the MESSAGES piece is "What do I want the user to see when he/she gets the required alert

4. ERROR PLACEMENT - this places the error message into the NEXT element.


Ok so here is part of my form:

<tr>
<td class="label"> <span class="alerttext4"> *</span>
<label id="institutionName" for="institutionName"> Name of Institution</label> </td>
<td class="field"> <input id="institutionName" size="45" name="institutionName" type="text" value="#form.institutionName#" /> </td>
<td class="status"> </td>
</tr>



See that last little TD that has nothing in it: <td class="status"> </td> - that is where the error message will be displayed. Nice and neatly placed on the right side of the field.

*ALL SMILES*

Let me know how it works out for you!

No comments:

Post a Comment