I see this all over the web, but was wondering if anyone has the JavaScript code for the EASIEST way to show input value on blur, but hide in on focus.
For all browsers:
<input onfocus="if(this.value == 'Your value') { this.value = '';}" onblur="if(this.value == '') { this.value = 'Your value';}" value="Your value" type="text" name="inputname" />
For newest version of browsers:
<input type="text" name="inputname" placeholder="Your value" />
I prefer jQuery way:
$(function(){
/* Hide form input values on focus*/
$('input:text').each(function(){
var txtval = $(this).val();
$(this).focus(function(){
if($(this).val() == txtval){
$(this).val('')
}
});
$(this).blur(function(){
if($(this).val() == ""){
$(this).val(txtval);
}
});
});
});
It is modified Hide Form Input Values On Focus With jQuery by Zack Perdue.
This is what I use on my blog. Just go there and check out the source code behind.
function displaySearchText(text){
var searchField = document.getElementById('searchField');
if(searchField != null)
searchField.value = text;
}
Your input field should look something like this:
<input id='searchField' name='q' onblur='displaySearchText("Search...");' onfocus='displaySearchText("");' onkeydown='performSearch(e);' type='text' value='Search...'/>
This always worked for me:
<input
type="text"
value="Name:"
name="visitors_name"
onblur="if(value=='') value = 'Name:'"
onfocus="if(value=='Name:') value = ''"
/>
If you don’t care about valid HTML, you use the placeholder
attribute. It will work out of the box on a Safari, and you can add some unobtrusive JS to mimic this behavior in other browsers.
More reading:
And google. ;-)
The solution is similar to the one Josh Stodola posted, but it’s more flexible and universal.
Since this still comes up on google, I'd like to point out that with HTML 5 you can use the placeholder attribute with an input to achieve this in one piece of html.
<input type="text" id="myinput" placeholder="search..." />
Placeholder is now standard across modern browsers, so this really would be the preferred method.