Insert default value if input-text is deleted
Posted
by Kim Andersen
on Stack Overflow
See other posts from Stack Overflow
or by Kim Andersen
Published on 2010-06-07T07:23:01Z
Indexed on
2010/06/07
12:02 UTC
Read the original article
Hit count: 468
Hi all
I have the following piece of jQuery code:
$(".SearchForm input:text").each(function(){
/* Sets the current value as the defaultvalue attribute */
if(allowedDefaults.indexOf($(this).val()) > 0 || $(this).val() == "")
{
$(this).attr("defaultvalue", $(this).val());
$(this).css("color","#9d9d9d");
/* Onfocus, if default value clear the field */
$(this).focus(function(){
if($(this).val() == $(this).attr("defaultvalue"))
{
$(this).val("");
$(this).css("color","#4c4c4c");
}
});
/* Onblur, if empty, insert defaultvalue */
$(this).blur(function(){
alert("ud");
if($(this).val() == "")
{
$(this).val($(this).attr("defaultvalue"));
$(this).css("color","#9d9d9d");
}else
{
$(this).removeClass("ignore");
}
});
}
});
I use this code to insert some default text into some of my input fields, when nothing else is typed in. This means that when a user sees my search-form, the defaultvalues will be set as an attribute on the input-field, and this will be the value that is shown. When a user clicks inside of the input field, the default value will be removed.
When the user sees an input field at first is looks like this:
<input type="text" value="" defaultvalue="From" />
This works just fine, but I have a big challenge. If a user have posted the form, and something is entered into one of the fields, then I can't show the default value in the field, if the user deletes the text from the input field. This is happening because the value of the text-field is still containing something, even when the user deletes the content. So my problem is how to show the default value when the form is submitted, and the user then removes the typed in content?
When the form is submitted the input looks like this, and keeps looking like this until the form is submitted again:
<input type="text" value="someValue" defaultvalue="From" />
So I need to show the default value in the input-field right after the user have deleted the content in the field, and removed the focus from the field.
Does everyone understand what my problem is? Otherwise just ask, I have struggled with this one for quite some times now, so any help will be greatly appreciated.
Thanks in advance, Kim Andersen
© Stack Overflow or respective owner