My code can do When clicking textbox, it empties the textbox. How to use jQuery to restore the default value if the nothing has been entered in the textbox?
7 Answers
$('input').focus(
function()
{
if ($(this).val() == defaultValue)
{
$(this).val('');
}
})
.blur(function()
{
if ($(this).val() == '')
{
$(this).val(defaultValue);
}
});
I would detect on load what the defaultValue is to use the user's data for a default if the page is a post back.
1 Comment
My answer is similar to Phil's where you store the contents in the data() for the object. Sort of like this (demo):
$('textarea')
.bind('focusin', function(e){
$(this)
.data('content', $(this).val())
.val('');
})
.bind('focusout', function(e){
if ( $(this).val() === '' ){
$(this).val( $(this).data('content'));
}
});
Comments
You can use something like this:
var defaultText = 'this is my default text';
var controlObject = $('#idControl');
controlObject.val(defaultText);
controlObject.focusin(function (e) {
var controlSelected = $(e.target);
if (controlSelected.val() == defaultText) {
controlSelected.val('');
}
}).focusout(function (e) {
var controlSelected = $(e.target);
if (controlSelected.val() == '') {
controlSelected.val(defaultText);
}
});
Comments
You can use following code for the textbox default value. It works for Textareas too. You just have to apply class "default-value" to all the text fields and textareas to whom you want to attach the default value functionality.
$('.default-value').each(function() {
$(this).data("default_value",$(this).val());
$(this).focus(function() {
if($(this).val() == $(this).data("default_value")) {
$(this).val("");
}
});
$(this).blur(function() {
if($(this).val() == '') {
$(this).val($(this).data("default_value")) ;
}
});
});
Another benifit of this code is that when you submit the form you can check if the field contains the original default value or not.
if( $(elem).val()==$(elem).data("default_value"))
{
//Contains default value
}
else
{
//Contains new value
}
placeholderattribute of the<input>element to whatever placeholder you need. This is the cleanest solution.