JQuery Textbox Hint
In most of the websites, you might notice textboxes with gray text inside which explains what is it for, and when you focus on the textbox it disappears and reappears when you leave the empty textbox.
To achieve this, what i do is:
– get the hint text from title attribute of textbox.
– Show hint text when textbox is empty and not in focus.
– Hide hint text when input box has the focus and title attribute matches input text.
See live Demo here and view the source if you’d like.
Let us take a sample HTML
<div id="block">
<input type="text" value="" title="search entire site" /> <br/><br/>
<input type="text" value="" title="Enter email address" /> <br/> <br/>
<input type="text" value="" title="Enter user name" />
</div>
Call the textbox hint function
$(document).ready(
function() {
textboxHint("block");
});
Here is the textboxHint function, it will take the input boxes container id and you can pass options like input box selector within a container and blur class. options parameter is optional, default selector is input:text[title] means input boxes which has title attributes and blur class is “blur“.
function textboxHint(id, options) {
var o = { selector: 'input:text[title]', blurClass:'blur' };
$e = $('#'+id);
$.extend(true, o, options || {});
if ($e.is(':text')) {
if (!$e.attr('title')) $e = null;
} else {
$e = $e.find(o.selector);
}
if ($e) {
$e.each(function() {
var $t = $(this);
if ($.trim($t.val()).length == 0) { $t.val($t.attr('title')); }
if ($t.val() == $t.attr('title')) {
$t.addClass(o.blurClass);
} else {
$t.removeClass(o.blurClass);
}
$t.focus(function() {
if ($.trim($t.val()) == $t.attr('title')) {
$t.val('');
$t.removeClass(o.blurClass);
}
}).blur(function() {
var val = $.trim($t.val());
if (val.length == 0 || val == $t.attr('title')) {
$t.val($t.attr('title'));
$t.addClass(o.blurClass);
}
});
// empty the text box on form submit
$(this.form).submit(function(){
if ($.trim($t.val()) == $t.attr('title')) $t.val('');
});
});
}
}
Here is the blur css that you can add in the head tag.
input.blur {
color:#808080;
}
Nice article. Simply working great! You have forgot to specify though that it needs a call to before this thing works; nonetheless, it helped me a lot.
sorry, the comment box stripped out the script.
it needs a call to script src=’http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js’
just download once..
Does this function work in email type ? thanks
Thanks nice and helpful article