Highlighting row on form error with jQuery
May 18th, 2009 by Matt
When showing errors in web forms, I thought it would be useful to highlight the row where the error occurred so the user can visually see where they they need to make changes. jQuery is the ideal way to do this for me as I didn’t want to do it server side.
To begin I set a CSS class on the error messages that were displayed in the td with the form element. An error message could be in the form of
<span class=".valError">You have selected an invalid date.</span>
Now all we have to do in jQuery is find all elements which match the class, remove any classes that may be on any of the td tags, then add a class to the tr in which the error exists.
$(".valError").each(function() { // remove all classes from any td's of the below the parent row $(this).parent().parent().find("td").removeClass(); // set the class on the tr $(this).parent().parent().addClass('ms-informationbar'); })
That’s it.
You could optionally set the class of the td rather than or as well as the tr. The following line would help you achieve this.
$(this).parent().parent().find("td").removeClass().addClass('myErrorClass');
Posted in jQuery