Flag This Hub

How To Create a Default Text Field Value That Disappears On Focus With jQuery

By


Most of the designs that come to me for development have a form element that has default text.  This is usually a search form with default text "Search Our Site" or an email signup form specifying that they should enter their email address.  Without additional code, it can be cumbersome for a user to click into these boxes and delete the default text in addition to entering their information.   To take advantage of the usability improvements default text gives us without adding additional work for the user, remove the default text when the user triggers the focus event of the textbox and re-insert the default text when the blur event is triggered and the textbox is empty.

HTML

<input name="searchText" title="Search Our Site" type="text" />

Instead of specifying my default value in the value attribute of the input tag, I specify it using the title tag.  I do this to prevent a problem when firefox saves the entered value, which would change our default value for the textbox.

JavaScript - jQuery

$("input[type=text][title]").each(function() {
  $(this).val($(this).attr("title"));
  if($.trim($(this).val()) == "")
    $(this).val($(this).attr("title"));
  $(this)
    .focus(function() {
      if($(this).val() == $(this).attr("title")) $(this).val("");
    })
    .blur(function() {
      if($.trim($(this).val()) == "") $(this).val($(this).attr("title"));
    });
});

This jQuery code should be executed within $(document).ready.

In addition to changing the text value for the textbox, we could specify classes to determine inactive and active states for the textbox.  With the specification of an id on a textbox, css could be applied differently for individual textboxes.

Comments

php rounded corners 21 months ago

works only for text fields, how about passwords? :(

jonkarna 21 months ago

I have done that before, but you have to work out a switch. Have the password field show up directly under the fake text field. When the text field gets clicked on, hide it, and put the focus on the password field.

[input class="text" id="real-password" name="password" tabindex="1002" type="password" value="" /] [input class="text" id="fake-password" name="fakepassword" tabindex="1001" type="text" value="" /]

$("input#fake-password").val("Password").focus(function() {

$(this).css("display", "none");

$("input#real-password").val("").css("display", "inline").focus();

});

$("input#real-password").blur(function() {

if($.trim($(this).val()) == "") {

$(this).css("display", "none");

$("input#fake-password").css("display", "inline");

}

});

Ozafy 20 months ago

Awesome, thanks.

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working