Reputation: 15925
I don't know if this has a special name for it, but is there a nice easy way to set default text in an input field which disappears on focus and reappears on blur if the textbox is empty?
Upvotes: 6
Views: 7479
Reputation: 54802
Here is my approach (with jQuery):
<input id="myBox" type="text" />
<script>
// Input field and default text
var $element = $('#myBox');
var defaultText = 'Hello World';
$element.focus(function(){
// Focused
$element.removeClass('defocused').addClass('focused');
if($element.val() == defaultText)
$element.val('');
}).blur(function(){
// Defocused
$element.removeClass('focused').addClass('defocused');
if($element.val() == '')
$element.val(defaultText);
});
// Initialization
$element.blur();
</script>
Upvotes: 0
Reputation: 1933
You can use this plugin (I'm an co-author)
https://github.com/tanin47/jquery.default_text
It clones an input field and put it there.
It works on IE, Firefox, Chrome and even iPhone Safari, which has the famous focus problem.
This way you do not have to be worried about clearing input field before submitting.
OR
If you want to HTML5 only, you can just use attribute "placeholder" on input field
Upvotes: 1
Reputation: 14135
You can use the new HTML5 placeholder attribute.
Edit: update to use some more HTML5/jQuery hotness, HTML5 data storage.
<input type="text" placeholder="type here" data-placeholder-text="type here" />
This will work on all modern browsers. And gracefully degrade in IE. However for IE you'll have to use javascript.
$(document).ready(function() {
var $input = $('#id_of_input_element');
$input.focus(function() {
if($(this).val() == $(this).data('placeholder-text')) {
$(this).val('')
}
}).blur(function() {
if($(this).val() == '') {
$(this).val($(this).data('placeholder-text'));
}
}).trigger('blur');
}):
Upvotes: 20
Reputation: 21864
the word is WATERMARK
I encourage to use a plugin, unless you have plenty of time developing and testing. There are many issues and side-effects to take notice of when writing this code.
Upvotes: 4
Reputation: 4400
The functionality is known as watermark , and can be acheived in many ways, one of them is
onfocus="if(this.value=='Enter Email')this.value=''"
onblur="if(this.value=='')this.value='Enter Email'"
This will work for email textbox.
Upvotes: 4
Reputation: 2488
you can try this: using the title attribute to store the default text
$(function(){
$(".makedefault").bind("blur",function(){
if($(this).val().length == 0)
{
$(this).val($(this).attr('title'));
}
});
$(".makedefault").bind("focus",function(){
if($(this).val() == $(this).attr('title'))
{
$(this).val("");
}
});
});
Upvotes: 2
Reputation: 11658
Here is solution.
$(".defaultText").focus(function(srcc)
{
if ($(this).val() == $(this)[0].title)
{
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".defaultText").blur(function()
{
if ($(this).val() == "")
{
$(this).addClass("defaultTextActive");
$(this).val($(this)[0].title);
}
});
$(".defaultText").blur();
Upvotes: 2