« Back to blog

Blog: Using jQuery to highlight required fields

Graham Weldon

20 March, 2009

One of the things that can get to be a pain in the bum to manage is the little indicator element that your designer has chosen to indicate required fields in a form.

The designer I am currently working with likes to use an asterisk to indicate a required field, and while that is not a problem, it gets fiddly and frustrating to manage down the line as form fields and required data changes through the evolution of a website. jQuery to the rescuse with a cross browser solution for CakePHP, inspired by the :after CSS pseudo class.

The following will, once the DOM is ready, find all required field and append the specified text to their labels. Its very quick, very simple, and means that as you update validation rules in your CakePHP models, the javascript handles juggling the asterisk indicator (in this example).

I agree with the bulk of you out there, and that this should be done with some CSS mechanism, and that asterisks are probably not the best way to indicate required information... However, it works, it eliminates my need to revisit the form after creating it, and overall makes me a happy chappy.

$(function() {
    $('.required label').append(' *');
});

Simple, easy, who could ask for more?

Comments