Feb. 28 2011

Setting form values with jQuery

Let’s say you have a form where you put field information in as the default value, like so:

<input type="text" name="email" class="cleardefault" value="E-mail address (required)" />

It’s really, really annoying for a use to have to go through and backspace through all that to start typing, so why not remove it for them using a little bit of jQuery magic?

Somewhere between your and tags, put this to include the jQuery library:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Now, you can put the following code somewhere before the tag. Anywhere is fine since it won’t take time to load:

<script type="text/javascript">
      var defaultvalue = $(this).val(); // Save the default value.
        if ($(this).val() == defaultvalue) $(this).val('');
        if ($(this).val() == '') $(this).val(defaultvalue);

What that little snippit did is:

  1. Looped through each input with class cleardefault.
  2. Using the focusin trigger (when the user clicks into the form field): if the user hasn’t changed the form field from the default value (which, you see, we captured on line 4), then we set the value to blank.
  3. Using the focusout trigger (or when the user clicks out of the form field):if the user hasn’t typed anything in the form field, then we change the value back to the default value.

That’s it! jQuery, as I’ve come to find out in the last couple of weeks, is pretty easy. I jumped feet first into it without any prior knowledge of Javascript or jQuery and I seem to be doing pretty good.

You can check out this snippit in action in the form of the comments section!

– Logan

Leave a Reply

Previous post:

Next post:

Last.fm interface from fmTuner (modified by me).

Twitter interface from HL Twitter.

Dedicated to my mom, Sharon. May she rest peacefully.
Love you always. (March 23, 1965 - November 12, 2011)

Unsupported Browser!

My site is designed for and currently displays best with modern browsers (and it looks like you don't have one!).

Everything should still function properly, but you won't be able to see all the fancy effects, text, or the way I intended my design to look.

Consider trying the latest version of either Firefox or Chrome... I think you'll like it!

Logan Bibby

P.S.: You can continue viewing my site by clicking the "close" link and you'll never see this again. :)