"Default Text" Fields Using Simple jQuery Trick

A lots of the time you want to add instructions to text box fields of the page to provide usability information to the users. Alternate way of doing this could be using default text in the input fields. A default text is the text which appears in the text box when it is empty. e.g.

Name
Email
Website
Comment

You can see this is useful and good idea to have this in the UI. There is an easy trick in jQuery to do this. Below is the step by step procedure to do this.

Step1

If you don't have jQuery then download latest from its website and include in you page.

<script src="jquery.js" type="text/javascript"></script>

Step 2

Create two CSS classes defaultText and defaultTextActive as mentioned below.

<style media="screen" type="text/css">
    .defaultText { width: 300px; }
    .defaultTextActive { color: #a1a1a1; font-style: italic; }
</style>

Step 3

Add this JavaScript to you page

<script language="javascript">
<!--
$(document).ready(function()
{
    $(".defaultText").focus(function(srcc)
    {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    $(".defaultText").blur(function()
    {
        if ($(this).val() == "")
        {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });
    
    $(".defaultText").blur();        
});
//-->
</script>

Step 4

To every text field or text area where you want to apply default text add "defaultText" as css class and specify the default text in the title attribute. e.g.

<input class="defaultText" title="e.g. someone@example.com" type="text" />

You default text setup is ready. Run the page and see the magic. Click here for a running sample page.

59 comment(S)


Bill on Aug 2, 2008 12:34 PM

What would you suggest doing in a case where the field might not be filled by the user. Currently the text that is being put in the title attribute is posted back? I would imagine there has to be a way using jquery to remove it on submit, but this is my first day looking into what is possible with jquery.

Bill on Aug 2, 2008 12:43 PM

I just found this plugin that removes the text prior to submit: http://plugins.jquery.com/project/ToggleFormText. I found it from a link in a Matt Berseth article http://mattberseth.c....xtboxwatermark.html.

SeanJA on Aug 3, 2008 10:08 AM

I think the code would probably look something like:

onSubmit(foreach(".defaulttext"){
if (title of field = content of field){
content of field = ""
}
}

I don't really know javascript, but it can't be that difficult to figure out.

SeanJA on Aug 3, 2008 10:09 AM

Awww... it lost its formatting...

SeanJA on Aug 3, 2008 10:11 AM

And looking at the plugin, that is exactly what it was...

Alex on Aug 13, 2008 01:58 AM

To clear the default text on submit:

<pre>
$("form").submit(function() {
$(".defaultText").each(function() {
if($(this).val() == this.title) {
$(this).val("");
}
});
});
</pre>

Vaibhav Gupta on Sep 12, 2008 01:08 AM

$("form_name").submit(function() {
$(".defaultText").each(function() {
if($(this).val() == $(this)[0].title) {
$(this).val("");
}
});
});

Rubist on Feb 10, 2009 06:22 AM

Yeah,

Its not removing the css class "defaultTextActive" if i use data picker of jquery

Andrew on Mar 21, 2009 03:15 PM

Hello,
on a page with multiple panels hiden and only one visible (wizard like), when I go back, the default text became none italic and none blur. So if i press the previous step button the default text looks like a regular one. In this case the (document).ready(function() not fired (it returns false so the (".defaultText").blur() is ignored). How could i call it?
Thanks.

sponsored

kav on Mar 21, 2009 06:01 PM

Refresh or reload this page and it will break down the italic and blur.

lewis on Mar 24, 2009 07:29 AM

If you are displaying error and setting values to the post values ... I used this to re-style the default text:
$.each($(".defaultText") ,function(){
if ($(this).val() == $(this)[0].title)
{
$(this).addClass("defaultTextActive");
}
});

,m.,m on Mar 31, 2009 03:05 AM

.m,.m,.

HeavyP on Apr 28, 2009 01:45 PM

FANTASTIC!!!
I've been hunting for something like this for days!
There is all sorts of different ways to skin this cat but working with multiple language and having the DEFAULT TEXT change too and load quickly was what I was looking for...and here it is!
Does someone know how to make the PASSWORD input field change from TEXT to PASSWORD on focus, remain PASSWORD if something is typed in but if nothing is typed in or it remains DEFAULT VALUE it returns to TEXT?
That would be pretty slick indeed!
Thanks.

Leandro Santana Pereira on May 3, 2009 07:23 PM

I fixed the bug that removes the italic when we reload or go back to the page put the following source into the begging of the document.ready:

$(".defaultText").each(function(){
$(this).addClass("defaultTextActive");
$(this).val(jQuery(this)[0].title);
});

Rinke van den Berg on May 20, 2009 11:11 PM

This also fixes it:
At the end of the document.ready put:

$(".defaultText").focus();
$(".defaultText").blur();

instead of just:

$(".defaultText").blur();

Might be a bit nicer because it uses the same functions (in case something changes in those functions).

By the way, I would come here more often if there were just banners instead of nasty popups.

Niyaz on May 30, 2009 07:46 AM

I am using this code in one of the web-apps I am developing.

Thank you very much.



leo on Aug 10, 2009 10:32 PM

The following link from cloudgen is similar to the example, however it is wrapped by a jQuery function:
http://cloudgen.w0ng.hk/jquery/defaultText.php

Jordi on Nov 25, 2009 11:13 AM

I have one text default plugin for jquery and I think that is more simply to use.

http://www.jordigiro....cto-formularios.html

Anton Venema on Jan 4, 2010 01:46 PM

Here's a short plugin variant I use. It improves default detection when the entered text matches the title, it incorporates Alex's fix for form submission, and it allows reuse throughout a site.

jQuery.fn.defaultText = function() {
var self = this;
$('form').submit(function() {
$(self).each(function() {
var t = $(this);
if (t.val() == t.attr('title') && t.hasClass('default')) {
t.val('');
}
});
});
return $(this).blur(function() {
var t = $(this);
if (t.val() == '') {
t.val(t.attr('title'));
t.addClass('default');
}
}).focus(function() {
var t = $(this);
if (t.val() == t.attr('title') && t.hasClass('default')) {
t.val('');
t.removeClass('default');
}
}).blur();
};
$(document).ready(function() {
$('input[type="text"]').defaultText();
});

Anton Venema on Jan 4, 2010 01:47 PM

Note that the last 3 lines are an example of how to use the plugin.

Danielle on Mar 18, 2010 08:27 AM

Very helpful. Thanks! Any ideas about how to detect when the browser autofills? I tried this:

$(".defaultText").live('focusin change', function() {

but to no avail.

yann on Mar 24, 2010 03:20 PM

Hi

Could someone elaborate a little on how to use those three lines with the function proposed by Anton please ?

thanks



yann on Mar 26, 2010 08:54 AM


Here is Anton's response :

The default text is attached as the "title" attribute of the DOM element:

<input type="text" title="Default text..." />

The call to $('input[type="text"]').defaultText(); will process all inputs of type "text" in the DOM tree, filling out the default text wherever it finds it as a "title" attribute.

Thanks again Anton

yann

Steve on Jun 7, 2010 05:03 AM

Tanks,..it's work to me..:)

Atiq on Jun 19, 2010 03:25 AM

Free Website Value Calculator

v

Hegemon on Sep 1, 2010 05:50 AM

This code is missing:

$("form:has(.defaultText)").submit(function(){
$('.defaultTextActive', this).val('');
});

pfsdfsdf on Sep 27, 2010 11:58 PM

fsdfsdf

john on Sep 28, 2010 12:35 AM

thanks for your work.. it's very useful

Anuj on Jan 26, 2011 02:32 PM

Thank you for this. Helped to learn alot.

Kris on Jan 30, 2011 01:31 PM

This code works great for a static page but i cant seem to get the default values to work when using it on a dynamic page.

Basically i am greating a page where the user can create more input fields by clicking a button, the input fields get created with the same look but with no default text.

The only thing i can think is that because the JQuery code only initiates on document load and these are created afterwards they are not getting registered (or something like that, today is my first time of using JQuery code).

Here is one of the elements being created

var newRow = tblChild.insertRow(rowCount);
newCell = newRow.insertCell(0);
newCell.align = tblChild.rows[1].cells[0].align;
newCell.innerHTML = tblChild.rows[1].cells[0].innerHTML;

The input tag is created exactly the same as my original.

Any ideas.

Kris

Dan on Feb 9, 2011 07:07 AM

@Kris

use .live() to attach the focus and blur events, e.g.

return $(this).live("focus", function() {
etc...
}).live("blur", function() {
etc...
});

CodeMan on Apr 30, 2011 09:16 AM

Same code, more compact:

$(document).ready(function()
{

$("#id").focus(function() {
$(this).val(($(this).val() == $(this)[0].title)?"":$(this).val());
});

$("#id").blur(function() {
$(this).val(($(this).val() == "")?$(this)[0].title:$(this).val());
}); $("#id").blur();

});

webdynamix on May 4, 2011 08:05 PM

Hi, I'm a newbie in jQuery abd I tried using some of the codes and I just got a problem clearing the fields with the default text upon submitting the form. can you please specify where should these codes located? (before the </head> or in any part of the body tag?)

jQuery.fn.defaultText = function() {
var self = this;
$('form').submit(function() {
$(self).each(function() {
var t = $(this);
if (t.val() == t.attr('title') && t.hasClass('default')) {
t.val('');
}
});
});
return $(this).blur(function() {
var t = $(this);
if (t.val() == '') {
t.val(t.attr('title'));
t.addClass('default');
}
}).focus(function() {
var t = $(this);
if (t.val() == t.attr('title') && t.hasClass('default')) {
t.val('');
t.removeClass('default');
}
}).blur();
};
$(document).ready(function() {
$('input[type="text"]').defaultText();
});


---for clearing the default textboxes upon submit---
$("form_name").submit(function() {
$(".defaultText").each(function() {
if($(this).val() == $(this)[0].title) {
$(this).val("");
}
});
});

Steve Klebanoff on May 10, 2011 04:32 PM

This works great, but I would make a few adjustments to make it a little 'sexier':

The first function does not need the 'srcc' parameter as its never used.

I personally like using $(this).attr('title') instead of $(this)[0].title, just looks a little cleaner to me.

Thanks for sharing this code, it is helpful and saved me some time.

Peace,
Steve

dfsdf on Jul 12, 2011 03:47 AM


Nick on Jul 13, 2011 05:09 PM

Has anyone written this into a Drupal module...? Specifically one that interact with the Webform module? Coz I'd love to know (searching hasn't turned up much).

This is a great feature and a great article I've referred to a few times. Definitely adds to a healthy UX.

Steven Benjamin on Jul 28, 2011 05:41 PM

This is probably a better way to do it.
http://pastebin.com/7NvbH4ux

Michael Schinis on Aug 3, 2011 06:11 PM

@Rubist , this fixes the datepicker..

$(".date").datepicker({ dateFormat: 'dd/mm/yy',
onSelect: function(){
$(this).removeClass("defaultTextActive");
}
});

Michael Schinis on Aug 3, 2011 06:11 PM

@Rubist , this fixes the datepicker..

$(".date").datepicker({ dateFormat: 'dd/mm/yy',
onSelect: function(){
$(this).removeClass("defaultTextActive");
}
});

Steve on Oct 21, 2011 06:03 AM

I was looking for a quick solution, it worked like a charm! Thnx!

Jeff Andersen on Oct 31, 2011 04:40 PM

Here's a better solution I think, nine lines and no extra class names or CSS files to mess around with:

$("input[default]").focus(function() {
if ($(this).val() == $(this).attr('default')) {
$(this).val('').css({color:'#000', fontStyle:'normal'});
}
}).blur(function() {
if ($(this).val() == '') {
$(this).val($(this).attr('default')).css({color: '#a1a1a1', fontStyle: 'italic'});
}
}).blur();

To use it, just have this code within some body.onload function, and all you have to do is add a 'default' attribute to any input fields you want affected (like <input type=text default='Search...' \\> )

Steve O on Nov 14, 2011 07:52 AM

Is there a nice way to apply this to a select box?

Prateek Joshi on Dec 9, 2011 05:57 AM

It doesn't work when we dynamically add the text box on click of the add more button. Please provide me a solution for this.

Boheme on Jan 2, 2012 02:53 PM

Of course, you could do that all in 5 to 10 lines of JS and without the deadweight of external libraries if you're a serious programmer and not a jQuery charlatan. For the sake of those who need it:

var TA = document.getElementsByTagName( "textarea" )
for( var i=0, j=TA.length; i<j; i++ ) {
TA[i].defaultValue = TA[i].value
//TA.style.fontStyle = "italic" // if you want a different look
//TA.style.color = "#cccccc" // yadda yadda, etc.
TA[i].onfocus = function() {
if( this.value == this.defaultValue ) {
this.value = ""
// this.style.fontStyle = "normal" // if you changed the style above
// this.style.color = "#000000" // ditto
}
}
}

I didn't think much about this and I tried it only in FFox, but it's simple enough & should work anywhere. Make sure you place this before loading the custom form content from a database/xml, so those loaded values do not get treated as defaults. If I used this for real, I'd have default values in an XML file so a soft-refresh (F5) would work right - in this "light" form, a custom-loaded or subsequently entered value might get interpreted as default on soft-refresh.

If you want something more customized, drop me a note at boheme.buddha@yahoo-dot-com and give me a day or two.

JackTheKnife on Jan 25, 2012 03:05 PM

I have try that code with jQuery validation plugin but it fails on validate process. Any idea why? Thanks

syedmohammedahmed on Mar 9, 2012 11:11 AM

check out this

this can help you
http://workwithphp.info/?p=8

Veerendra on Mar 22, 2012 08:10 PM

Thank you. It saved some of my time.

kris on Apr 17, 2012 12:19 AM


Excellent stuff - but now - with HTML4 - no longer even necessary.
Check out the "placeholder" option :

<input type="text" placeholder="e.g. someone@example.com">


kris on Apr 17, 2012 12:21 AM

Update to the above - HTML5, not 4, gives you this.

Also there are all new input types so you can actually say

<input type="email" placeholder="e.g. someone@example.com">

Works the same as type="text" in any old browser, and some new user agents might even give you a special way to input an "email" (eg. phones might give you a special key pad when entering an email address with the @ sign is already there)

ggf on Jun 5, 2012 12:40 AM


signe on Nov 7, 2012 05:59 PM

@HeavyP, for password input fields you can use jQuery to temporarily change the type of input field to text when not focused and field is empty:
$('.default-text').focus(function() {
var inputField = $(this);
if (inputField.val() == inputField[0].title) {
inputField.prop('type', 'password');
inputField.removeClass('default-text-active');
inputField.val('');
}
});
$('.default-text').blur(function() {
var inputField = $(this);
if (inputField.val() == '') {
inputField.prop('type', 'text');
inputField.val(inputField[0].title);
}
});
$('.default-text').blur();

signe on Nov 7, 2012 06:07 PM

gahhh silly me I didn't test the code properly which caused all input fields to become password type. Anyway a quick fix would be to add an arbitary attribute to the password input field (here i named it data-type):

<input type="password" title="password" data-type="password">

and the updated code:

$('.default-text').focus(function() {
var inputField = $(this);
if (inputField.val() == inputField[0].title) {
if (inputField.attr('data-type') == 'password') {
inputField.prop('type', 'password');
}
inputField.removeClass('default-text-active');
inputField.val('');
}
});
$('.default-text').blur(function() {
var inputField = $(this);
if (inputField.val() == '') {
if (inputField.attr('data-type') == 'password') {
inputField.prop('type', 'password');
}
inputField.prop('type', 'text');
inputField.val(inputField[0].title);
}
});
$('.default-text').blur();

Benito on Feb 7, 2013 12:14 PM

Why not just use Placeholder?

<input type="password" placeholder="password" data-type="password">

jonny on May 8, 2013 05:21 PM

This script below will work for password fields.

<input type="text" class="text watermark" watermark="email" name="username" value="" />
<input type="password" class="password watermark" watermark="password" name="password" value="" />


$(document).ready(function() {

show_watermarks();
$("input.watermark").focus(focus_watermark);
$("input.watermark").blur(blur_watermark);
});

function show_watermarks()
{
$("input.watermark").each(function(idx){

if($(this).val().length == 0)
{
if($(this).attr('type') == 'password')
{
// set type to text so we can read the watermark
$(this).attr('type', 'text');
}

$(this).val($(this).attr('watermark'));
}
});
}

function focus_watermark(e)
{
if($(this).val() == $(this).attr('watermark'))
{
// remove watermark
$(this).val('');

// if password field, change type back to password
if($(this).hasClass('password'))
{
$(this).attr('type', 'password');
}
}
}

function blur_watermark(e)
{
if($(this).val().length == 0)
{
// add watermark
$(this).val($(this).attr('watermark'));

// if password field, change type to text
if($(this).hasClass('password'))
{
$(this).attr('type', 'text');
}
}
}

Ingrid on Jun 10, 2013 02:23 PM

Thanks to all for the follow up comments to the original code--all has been very helpful. I'm wondering how to submit on keypress without the 'defaultTextActive' class showing. Submitting with the onclick works fine, but if I hit the enter key the onblur 'defaultTextActive' is not clearing...

1212 on Jun 12, 2013 12:42 AM


xxx on Jul 23, 2014 05:02 AM

ikiii

CaptainHuge on Dec 8, 2014 01:05 PM

This is not the solution you want if you need to validate your form with "required" fields - if the title attrib is being written into the field as .val(), then the title attribute becomes the default field value and your users will end up submitting forms with default values that passed "required" validation.

Leave a comment