jQuery Plugin – Form Field Default Value

by Jason on August 24, 2008

Note: find the latest version of this plugin on Github!

So I just finished writing my first jQuery plugin!  The idea behind it is simple – provide a dead simple way to apply a default value to any text-based form field.

In it’s current state, my plugin accomplishes the following:

  1. Provides a simple way to apply a default value to any text-based form field.
  2. Only shows default value for EMPTY form fields.
  3. Default value returns to an empty form field when it’s lost focus.
  4. Upon submitting the form, fields which still contain the default value are set to empty

Example Usage:

$(“#myfield”).DefaultValue(“My Default Value..”);

View Demo

Download

I’m sure there are other plugins that satisfy these requirements and I’m not claiming that this is the best in the world, but it satisfies all my requirements and gave me the opportunity to develop my first jQuery Plugin!

I may enhance the plugin soon to incorporate styling to form fields.

48 comments

doesnt seem to work for password fields. its masking the default values

by ct on September 5, 2008 at 12:10 pm. #

Well – it will apply a default value to a password field, but password fields are inherently “masked”, and for good reason. I wouldn’t want someone seeing my password on-screen, even if it were a default value.

by Jason on September 5, 2008 at 12:22 pm. #

I’ve updated the demo to show how this plugin works with password fields. Let me know if this helps!

by Jason on September 5, 2008 at 12:27 pm. #

Seems that if you use the script on a class of items (i.e. you get an array back), something goes wrong.

I changed
el.val(def).focus(function() {

to el.val(def);
el.focus(function() {

and it worked again. Still suboptimal, because it then will blank all controls, even if you only selected one, but in my case that’s not too horrible.

by Jan on September 10, 2008 at 8:43 am. #

Thanks for the bug report Jan! I’ll take a look and have a fix as soon as I can.

Thanks again

by Jason on September 10, 2008 at 8:51 am. #

How different is this from $(“#fieldname”).attr(“defaultValue”) ?

by Brinley Ang on November 2, 2008 at 8:40 pm. #

Jason,

Great work! I know you mentioned that this wont work with password fields because of their masked nature. But if you look at facebook, somehow they figured it out on their login page. It shows “Password” for the password field until you click on it? Maybe they are rewriting the field once you click on it to change states?

what do you think?

by Jake Rutter on November 28, 2008 at 6:04 am. #

[…] that way, but the search began for a better (read: functional) solution. Enter Jason Palmer and his jQuery Form Field Default Value plugin. Not to steal any of Jason’s thunder, but the plugin is elegant and doesn’t […]

by A Real American Hero » Blog Archive » Actually handling blanking default form input values… in all browsers on December 5, 2008 at 10:26 am. #

Hi Jason,
thanks for good plugin, but I have one problem. After first load is all OK, but after press F5 key, there remains default text in plugin but after click in input, text doesn’t disappear (in all browsers).

And one notice.. I would appreciate if there was option to have password in input (default value) masked or not (for example: write in word “password”).

by Lukas on December 19, 2008 at 1:25 pm. #

I’ve updated the code to have gray default coloring return (initiate it with a gray css):

//Remove values on focus
$(this).focus(function() {
if(this.value==text || this.value==”){
this.value=”;
$(this).css({‘color’ : ‘black’});
}
});

//Place values back on blur
$(this).blur(function() {
if(this.value==text || this.value==”){
this.value=text;
$(this).css({‘color’ : ‘gray’});
}
});

by Brett on January 16, 2009 at 3:52 pm. #

Actually… I just realized that it’s best to initiate the gray from within the script too:

//Set value initially if none are specified
if(this.value==text || this.value==”) {
this.value=text;
$(this).css({‘color’ : ‘gray’});
}

//Remove values on focus
$(this).focus(function() {
if(this.value==text || this.value==”){
this.value=”;
$(this).css({‘color’ : ‘black’});
}
});

//Place values back on blur
$(this).blur(function() {
if(this.value==text || this.value==”){
this.value=text;
$(this).css({‘color’ : ‘gray’});
}
});

by Brett on January 16, 2009 at 3:56 pm. #

Jason,
Great plugin, It’s a nice little utility that just saved me some time under a tight deadline. Thanks for sharing.

Two little nitpicks,
1. It fails if you’re using it with jQuery’s noconflict mode. That’s easily fixed by changing all instances of ‘$(‘ to ‘jQuery(‘.

2. There’s an edge case where someone will put a value in a field, refresh the page (their inputted value is retained), and then the focus and blur actions are not applied. You can fix this by removing the ‘return’ statement on line 15. I dont’ think it’s needed for anything else, unless you explicitly didn’t want to add the focus and blur handlers for some reason.

Anyways, thanks again!

by Robby on March 11, 2009 at 12:29 pm. #

OMG! Thx Dude, just what i needed :-)

by William on May 2, 2009 at 6:23 am. #

Jason, Great plugin man! Really helps for sites that use a lot of inputs and need default text in them. Little bug in firefox though. If you go to a page, on first load it works, but if you simply refresh it not longer works (just a firefox thing).

Fixing it is easy, on this line:

//Set value initially if none are specified
if(this.value==”) {

Just add:

//Set value initially if none are specified
if(this.value==” || this.value == text) {

Boom fixed and works great in all browsers!

by Clark on May 28, 2009 at 3:32 pm. #

Tx jason. Nice n nifty. Well, i read d comments n realized reg the problem wid password field. Lucky me, im not using it in a login form ;). Anyways, lemme know once if the password-problem is fixed. I have a bunch of developers im guiding, i would love to pass this onto them.

by satya on July 19, 2009 at 4:48 am. #

great plugin Jason this is just what I was looking for! Nice work!

by phil on August 10, 2009 at 3:57 am. #

Jason, thanks for sharing this code… We just start using a modified version of your plugin in Cherokee-Admin (http://www.cherokee-project.com)

This is the modified version. I have added a new parameter (class) to change the class of the input element.

jQuery.fn.DefaultValue = function(klass, text){
return this.each(function(){
//Make sure we’re dealing with text-based form fields
if (this.type != ‘text’ && this.type != ‘password’ && this.type != ‘textarea’)
return;

//Store field reference
var fld_current = this;

//Set value initially if none are specified
if($(this).val() == ”) {
$(this).val(text);
} else {
//Other value exists – ignore
return;
}

//Remove values on focus
$(this).focus(function() {
if($(this).val() == text || $(this).val() == ”) {
$(this).removeClass(klass);
$(this).val(”);
}
});

//Place values back on blur
$(this).blur(function() {
if($(this).val() == text || $(this).val() == ”) {
$(this).addClass(klass);
$(this).val(text);
}
});

//Capture parent form submission
//Remove field values that are still default
$(this).parents(“form”).each(function() {
//Bind parent form submit
$(this).submit(function() {
if($(fld_current).val() == text) {
$(fld_current).val(”);
}
});
});
});
};

by SKaRCHa on August 30, 2009 at 11:37 am. #

Hi SKaRCHa,

It’s great to hear that you’re using it for your site. BTW, the cherokee project looks very promising!

As you can see, several developers have created updates to the plugin over the past few months. In the next few weeks, I’ll be updating the plugin with some of these features/fixes.

Check back soon!

by Jason on August 31, 2009 at 12:30 pm. #

We are not using in the website, but in web application (Cherokee-Admin) to configure Cherokee web server.

I’ll be tuned… Thanks again! ;)

by SKaRCHa on September 1, 2009 at 5:30 am. #

Thanks for the code Jason. Made a few updates to it so it would work with our project.
– Fixed refresh bug
– Fixed plugin bug so it will work with jQuery’s noconflict mode
– Added trim so it will remove whitespace in the fields and show the default values if there is only whitespace
– Added the class support from SKaRCHa (fixed refresh class update bug)

===========================
(function($) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,””);
}
$.fn.DefaultValue = function(klass,text) {
return this.each(function() {
//Make sure we’re dealing with text-based form fields
if (this.type != ‘text’ && this.type != ‘password’ && this.type != ‘textarea’) {
return;
}

//Store field reference
var fld_current = this;
var fldVal = this.value.toLowerCase().trim();
var textVal = text.toLowerCase().trim();

//Set value initially if none are specified
if (fldVal == textVal || fldVal == ”) {
$(this).addClass(klass);
this.value = text;
}

//Remove values on focus
$(this).focus(function() {
var fldVal = this.value.toLowerCase().trim();
if (fldVal == textVal || fldVal == ”) {
this.value = ”;
$(this).removeClass(klass);
}
});

//Place values back on blur
$(this).blur(function() {
var fldVal = this.value.toLowerCase().trim();
if (fldVal == textVal || fldVal == ”) {
$(this).addClass(klass);
this.value = text;
}
});

//Capture parent form submission
//Remove field values that are still default
$(this).parents(“form”).each(function() {
//Bind parent form submit
$(this).submit(function() {
if (fld_current.value.toLowerCase().trim() == textVal) {
fld_current.value = ”;
}
});
});
});
};
})(jQuery);
===========================

by Todd on February 3, 2010 at 5:45 pm. #

This doesn’t seem to work with jquery 1.4.2 any ideas as to why???

by Emmanuel on March 26, 2010 at 8:41 am. #

Never mind it works.. I did a trick with a hidden password field to show/hide it so it looks like password fields have a default text and when clicked they get changed to *** ;)

by Emmanuel on March 26, 2010 at 8:45 am. #

Here is the code:

jQuery.fn.DefaultValue = function(text,hidden_password_field){
return this.each(function(){
var mInputName = this.id;
//Store field reference
var fld_current=this;
//Make sure we’re dealing with text-based form fields
if(fld_current.type != ‘text’ && fld_current.type != ‘password’ && fld_current.type != ‘textarea’)
return;

//Set value initially if none are specified
if(fld_current.value==”) {
fld_current.value=text;
if(fld_current.type==’password’ && hidden_password_field!=”){
$(“#”+hidden_password_field).val(text);
$(“#”+mInputName).val(“”);
$(“#”+mInputName).hide();
}
} else {
//Other value exists – ignore
return;
}

//Remove values on focus
$(fld_current).focus(function() {
if(fld_current.value==text || fld_current.value==”){
fld_current.value=”;
}
});

if(fld_current.type==’password’ && hidden_password_field!=”){
$(“#”+hidden_password_field).focus(function() {
$(“#”+hidden_password_field).hide();
$(“#”+mInputName).show();
$(“#”+mInputName).focus();
});
}

//Place values back on blur
$(fld_current).blur(function() {
if(fld_current.value==text || fld_current.value==”)
fld_current.value=text;
if(fld_current.type==’password’ && hidden_password_field!=”){
$(“#”+hidden_password_field).show();
$(“#”+mInputName).hide();
$(“#”+mInputName).val(“”);
}
});

//Capture parent form submission
//Remove field values that are still default
$(fld_current).parents(“form”).each(function() {
//Bind parent form submit
$(fld_current).submit(function() {
if(fld_current.value==text) {
fld_current.value=”;
}
});
});
});
};

In HTML use like thius:
Javascript:
$(document).ready(function() {
$(“#passwordFld”).DefaultValue(“Type your Password”,”passwordMask”);
});

Body:

by Emmanuel on March 26, 2010 at 8:51 am. #

Thanks for all your work on the plugin, it’s is exactly what I need except for one issue which is a bit unique to my situation.
The form that I am using this on uses the Person’s Last Name as their password, so I need the default text to say “Last Name” instead of being masked but then be masked once they input their value.

Is this possible?

by Joel on March 26, 2010 at 9:42 am. #

Hey, Jason! It’s quite unconvinient to do so in javascript, ’cause it’s more convinient to set default field value in the html code itself:

Everything you need to do with it – add some handlers, that will use safe ALT attribute to store default value and add some code to onload event:

jQuery(document).ready(function(){

$(“input”).each(function() {
$(this).attr(“alt”, $(this).attr(“value”));
});

$(“input”).focus(function(){
if ($(this).attr(“type”) == “text” && $(this).attr(“value”) == $(this).attr(“alt”))
$(this).attr(“value”, “”)
});

$(“input”).blur(function(){
if ($(this).attr(“type”) == “text” && $(this).attr(“value”) == “”)
$(this).attr(“value”, $(this).attr(“alt”))
});

});

That’s all! Graceful degradation is preserved! Good luck!

by Alexander Shlygin on April 16, 2010 at 6:54 am. #

Otherwise, you can user “title” attribute to store default value for the field, so you can save your data validation after page is resfreshed.

In this case, you do not need .each assignment anymore, just comparing value and title on focus and blur event!

Less code, do more!

by Alexander Shlygin on April 16, 2010 at 7:09 am. #

Hi Alexander,

Great & valid points! However, contrary to your statement, my current solution provides “backward compatibility just as yours does. Let’s assume a user does not have JavaScript enabled. Both yours and my solution will result in that user not seeing anything in the input box.

I agree your solution is a bit more compliant with HTML standards, however it doesn’t provide a “backup” for users without JavaScript. Seems HTML5 offers some functionality related to this.

by Jason on April 17, 2010 at 9:17 pm. #

Hi, Jason!

Thank you for your reply! I do not really see such a problem in this case: you can leave default value hardcoded in html, so users will see this value neither they have enabled javascript or not. And this default value will be processed the same way/

On the other hand, it is rather hard to find a user without javascript enabled nowadays.

Or may be I did not understand your point.

P.S.: Sorry for making you think, that your solution is not backward compilant for me. I meant that my is doing well too!

by Alexander Shlygin on April 18, 2010 at 4:14 pm. #

i want to make function in which argument will be pass jQuery object which is id of form.and return value of function should be map of name-value pair of each elaement in form.how can i do that?>

by tina on May 10, 2010 at 10:23 am. #

Thanks for your simple but usefull plugin!

by Jiri on June 5, 2010 at 2:35 pm. #

Hi Jason,

ive been searching for something like this, and as such wanted to ask permission to use this as a base for our contact forms we develop for our templates and sell on themeforest, woudl greatly appreaciate a response.

Thanks

Christian

by christian on June 21, 2010 at 3:59 am. #

Of course – free as in beer :)

Enjoy.

by Jason on June 23, 2010 at 10:25 am. #

Thanks Jason, appreciate it!

by christian on June 24, 2010 at 8:52 am. #

Upon submitting the form, fields which still contain the default value are set to empty and if a form validation script stops the submitting process I end up with a bunch of empty fields.
How can I fill the empty fields with the default values back?

by Julian on August 11, 2010 at 1:09 pm. #

[…] , 找到了Form Field Default Value这篇博客, 作者写了一个jquery插件,代码如下 jQuery.fn.DefaultValue = […]

by 在表单中设置默认值 » Eric Lo on August 23, 2010 at 6:56 am. #

Nice Job Jason :)
replace focus with onmouseover

by nils on March 16, 2011 at 7:00 am. #

hi,

I am having trouble with $(‘.default-value’), I am using validationEngine plugin but still can’t figure it out that from where this $(‘.default-value’) comes, I will appreciate any kind of help

thanks,

by Jenifer Smith on April 13, 2011 at 5:20 am. #

I have the same question as Julian on August 11, 2010 :

Upon submitting the form, fields which still contain the default value are set to empty and if a form validation script stops the submitting process I end up with a bunch of empty fields.
How can I fill the empty fields with the default values back?

by Luc on May 22, 2011 at 1:35 am. #

Hi Luc,

Please have a look at the code below. I spent some time this morning integrating my plugin with the jQuery Validator plugin and coded up a simple way around the issue you guys are having. Please see below and let me know if you have any questions.


$(document).ready(function() {
//Initially set default values
set_defaults();

//Configure form validator
var $validator = jQuery("#testform").validate();
$validator.settings.showErrors = function(){
//Reset default values
set_defaults();

//Call default show errors
$validator.defaultShowErrors();
}
});

function set_defaults(){
//Assign default value to form field #1
$("#fname").DefaultValue("Enter your first name..");
$("#lname").DefaultValue("Enter your last name..");
$("#desc").DefaultValue("Describe yourself...");
}

by Jason on May 22, 2011 at 7:05 am. #

Not sure if you plan to update this script, but it doesn’t work with jQuery 1.6x. Any thoughts?

by Dennis Deacon on May 26, 2011 at 9:04 am. #

Hi Dennis,

I wasn’t aware that the plugin didn’t work under 1.6. I’ll run a few tests this weekend and push out an updated version.

As soon as it’s ready I’ll post another blog and link this article to the new one.

Thanks for bringing it to my attention.

by Jason on May 26, 2011 at 6:27 pm. #

Hi!

For Jquery 1.6 use this code
jQuery(“#fname”).prop(‘defaultValue’);

Previous: its used .attr(‘defaultValue’);

Hope this help to some one..

by The UK Flights on July 12, 2011 at 3:47 pm. #

Hey, Thanks for giving such a nice plugin to us. Here in my application, I am facing a problem. I have form with two buttons(submit, reset). When I click on reset, it is clearing the default values also. Could you please help me out in this.

Thanks
deadmaN

by DeadMan on September 21, 2011 at 5:33 am. #

Hi,,

I have a solution to this issue. I don’t know whether its works in all conditions. I tested few. It works fine with my application.
(I am having trouble with $(‘.default-value’), I am using validationEngine plugin but still can’t figure it out that from where this $(‘.default-value’) comes, I will appreciate any kind of help). I modified the plugin’s code in

FROM:
//Capture parent form submission
//Remove field values that are still default
$(this).parents(“form”).each(function() {
//Bind parent form submit
$(this).submit(function() {
if(fld_current.value==text) {
fld_current.value=’ ‘;
}
});
});
TO:

//Capture parent form submission
//Remove field values that are still default
$(this).parents(“form”).each(function() {
//Bind parent form submit
$(this).submit(function() {
if(fld_current.value==text) {
fld_current.value=text;
}
});
});

I mainly modified fld_current.value =’ ‘ to fld_current.value=text. It works fine with my application.

Thanks,
deadmaN

by DeadMan on September 21, 2011 at 5:45 am. #

Hmmm….

$.fn.defaultValue = function(v)
{
// defaultValue plugin
this.blur(function(){
if($(this).val() == '')
$(this).val(this.defaultValue);
});
this.focus(function(){
if($(this).val() == this.defaultValue)
$(this).val('');
});
}

$('input').defaultValue();

by Sulik on February 14, 2012 at 12:04 pm. #

Nice, was looking for something like this…

by Christopher on April 30, 2012 at 3:11 am. #

Hi,
Thanks for the script! I’m hoping you can help me .. I’m using this in a signup form that pops up in a lightbox (thickbox) and the defaults don’t load when the lightbox is first loaded. if you close and load it again, they show but wondering how i can eliminate fields being blank on first load?

thanks in advance, Jen

by Jen on June 20, 2012 at 11:31 am. #

Hi,
Thanks for this script!It’s a simple but used commonly.
Sorry for my poor english :D

by ando on December 13, 2013 at 10:21 pm. #

Leave your comment

Required.

Required. Not published.

If you have one.