Reputation: 38265
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?
Upvotes: 2
Views: 8295
Reputation: 6042
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
}
Upvotes: 0
Reputation: 71
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);
}
});
Upvotes: 1
Reputation: 105
I do it this way;
$('#textbox').focus(function(){
if($(this).val() == 'Enter some text..')
$(this).val('');
}).blur(function(){
if($(this).val() == '')
$(this).val('Enter some text..');
});
Upvotes: 0
Reputation: 597
$('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.
Upvotes: 6
Reputation: 86463
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'));
}
});
Upvotes: 5
Reputation: 16858
Assuming you don't want to use placeholders or other HTML5-y goodness, try the following:
$('#myTextbox').click(function(){
$(this).data('saved-text', $(this).val());
// Now you can clear your text.
}).focusout(function(){
$(this).val($(this).data('saved-text'));
});
Upvotes: 1