Code Snippet
Set/Clear Default Input Value
$('.default-value').each(function() {
var default_value = this.value;
$(this).focus(function(){
if(this.value == default_value) {
this.value = '';
}
});
$(this).blur(function(){
if(this.value == '') {
this.value = default_value;
}
});
});
This is very old snippet. Now you better use placeholder or equiwalent. And one important thing – whats about send value? You set the default, but sometimes this is wrong.
Considering ‘placeholder’ is part of HTML5, this JS method would be a safe fall back for older browsers…
Not sure what the problem with the ‘send value’ is though; if the field is empty this will apply the input tag’s default ‘value’, if the field is not empty then it holds whatever was entered.
With my form, I have fields that are not required but have pre-filled value text as a usability hint. Several of these fields go through various types of validation (right number of characters, etc).
How would i clear only the default value of those specific fields?
example:
I need to clear the “Enter promotion code” on submit so that the value doesn’t go through validation and trigger an alert.
If you are aiming at newer browsers (or if accommodating older browsers is not a problem) it would be better to set it up like this:
[code][/code]
Although, to use this JS method, include the provided script in your page and use the following:
[code][/code]
My bad… Too used to forum code tags.
For HTML5 ‘placeholder’ method:
For JS ‘value’ method:
What the heck? Ok… Let’s just do it this way: For this JS method just add class=”default-value” to the input tag and leave everything else the way you have it.
Unfortunately, this has to work in ie6 as well. Currently I have a span underneath the input field to simulate the functionality. But I don’t want to do it that way.
The two forms where I’m using this are one input forms. For the submit, would it be possible to throw out the default value using onclick or onsubmit?
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.