Share
  • Share this post on Delicious
  • StumbleUpon this post
  • Share this post on Digg
  • Tweet about this post
  • Share this post on Mixx
  • Share this post on Technorati
  • Share this post on Facebook
  • Share this post on NewsVine
  • Share this post on Reddit
  • Share this post on Google
  • Share this post on LinkedIn

jQuery makes marking required fields easy!

jquery

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.

About the author

Tawnos has written 5 articles for Wednesday Night Magic

1 Response to "jQuery makes marking required fields easy!"

  • davelahaye 01:08 AM 12/10/2011

    That syntax code writer looks really good! Glad you found something that will work for the site.

Leave a Reply

Site Sponsors

A special thanks to Dave LaHaye and Brent Clark of Bullfrog Sweatshop for all of their help with this site! Check them out if you need some web work done, we highly recommend them!