jQuery makes marking required fields easy!
Anyone who has written a web form from scratch knows that managing required fields is essential. There are tons of ways to validate forms that will determine the structure of your HTML code but there are only a handful of standard places to put a marker that shows a field is required. In general those places are:
- After the input
- Before the input
- After the label
- Before the label
jQuery makes this task extremely simple and cuts down on a ton of HTML code. Take for example a form to accomplish task… whatever. This form has a field called e-mail and that field is required. The HTML for the input element that captures the e-mail address might look like this:
<label for="email">Email</label> <label for="email">Email</label> <input id="email" type="text" name="email" />
That will work just fine but let’s say you want to show that this field is required. You might add a span with an asterisk (*) after the input. So your HTML would look like:
<label for="email">Email</label> <input id="email" type="text" name="email" /> <span class="req">*</span>
Great! Now lets say you have 20 of these to do. Do you really want to be manually adding in that span every time? Probably not. An alternative is to add to your input element and then add some jQuery to your page. The HTML would then look like this:
<label for="email">Email</label> <input id="email" class="required" type="text" name="email" />
And the jQuery would be:
$('input.required').each(function(){ $(this).after('*'); });
This will add an asterisk with?the CSS class “req” to after each input element marked as required. You want the asterisk before the field? Then do this:
$('input.required').each(function(){ $(this).before('*'); });
Want the asterisk at the end of the label preceding the input? This will do it:
$('input.required').each(function(){ $(this).prev('label').after('*'); });
Now you have a simple to use jQuery block that marks all of your required fields with the simple addition of a CSS class. Stay tuned for next time when I talk about form validation using jQuery.
jQuery makes marking required fields easy!
That syntax code writer looks really good Glad you found something...
What's The Deal With Content Management Systems?
I am new to Wordpress but have followed its progress for...
Goblins? Joblins!
I love this deck except when I am playing against it...