jQuery Plugin – Form Field Default Value
by Jason on August 24, 2008
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:
- Provides a simple way to apply a default value to any text-based form field.
- Only shows default value for EMPTY form fields.
- Default value returns to an empty form field when it’s lost focus.
- Upon submitting the form, fields which still contain the default value are set to empty
Example Usage:
$(“#myfield”).DefaultValue(“My Default Value..”);
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.
34 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. #