jQuery Input Text Replacement
Edit (July 1, 2011): This snippet has been dated for years.
A Modern Approach
If you need something quick that targets modern browsers you might want to consider using the HTML5 placeholder attribute instead of a javascript solution. Cross-browser support isn’t the best (it doesn’t look like IE9 supports it at all, but if the placeholder text isn’t critical to the functionality it might be the right solution.
Further reading on the placeholder attribute.
If that won’t do it, check out this Cross-Browser HTML5 Placeholder Text on Web Designer Wall if you’re looking for something more modern.
Finally, you can do it with jQuery (or plain ol’ Javascript) as my original post from 2008 demonstrates…
Thought I’d save this handy dandy function for later.
Makes the text in an input disappear when you click on the input.
The Function
var originalvalue = input.val();
input.focus( function(){
if( $.trim(input.val()) === originalvalue ){ input.val(""); }
});
input.blur( function(){
if( $.trim(input.val()) === "" ){ input.val(originalvalue); }
});
}
enio said:
teste
Ben said:
Oh. Did you think my comment form used the script? HA HA. That would only make sense of me to do. Um. I’ll have to implement it later as I’m in Nice at the moment.
SRYS.
Jalen said:
You’ve hit the ball out the park! Increbldie!
skylar saveland said:
AH .val() .. now I remember!
tdskate said:
Very nice. I was looking for this!
zarne said:
can i use $(input[type=text]) as the parameter??
Ben said:
Yup, anything that returns an input/textarea should be fine.
moritz said:
not really,
I had to use this:
$(‘input[type=text]‘).each(function(index, obj){
textReplacement($(obj));
});
Ben said:
Anything that returns an input/textarea should be fine.
An array is a different story :). You’re correct, the function isn’t made to handle more than one element.
maya said:
nice man, nice…i love jquery
leesangbin said:
i want to join with you
lau' said:
and what if I want to write “Click to Disappear” in the textbox?
xRommelx said:
thank you for this bro
really useful
this is the code i use
$(‘#buscardor’).focus(
function(){
if($.trim($(this).val()) == $(this).val()){
$(this).val(”);
}
}
);
$(‘#buscador’).blur(
function(){
if($.trim($(this).val()) == ”){
$(this).val($(this).val)
}
}
)