Reputation: 23
My code doesn't run and I want the value to be cleared when you click on another
what am I doing wrong?
var placeholderText = $('input').val();
$(placeholderText).focus(function() {
$(this).attr('value', "");
});
$(placeholderText).blur(function() {
$(this).attr('value', phTextVal);
});
Upvotes: 2
Views: 148
Reputation: 92893
You're using 'placeholderText' as a selector, which won't select anything. Use $('input').focus(...
and $('input').blur(...
instead.
UPDATE
If you want to store the existing value, and then replace it, then store it as .data()
in the <input>
element itself:
$('input').focus(function() {
$this = $(this);
$this.data('oldval',$this.val());
$this.val('');
});
$('input').blur(function() {
$this = $(this);
$this.val($this.data('oldval'));
});
http://jsfiddle.net/mblase75/AL2vS/12/
Or possibly:
$('input').blur(function() {
$this = $(this);
if ($this.val().length==0) { // only if the field is blank
$this.val($this.data('oldval'));
};
});
Upvotes: 4
Reputation: 715
How about using object.defaultValue property?
function:
$.fn.smartInput=function(){
return this.each(function(i,o){
$(o).focus(function(){ if(this.value==this.defaultValue) this.value='';})
.blur(function(){ this.value=(this.value=='')?this.defaultValue:this.value;});
});
}
usage:
$('input').smartInput();
Upvotes: 0
Reputation: 553
I guess the better way is:
var placeholderText = $('input');
$(placeholderText).focus(function() {
phTextVal = $(this).val();
$(this).val("");
}).blur(function() {
$(this).val(phTextVal);
});
Upvotes: 0
Reputation: 7612
Check it out,
$('input').focus(function() {
placeholderText = $('input').val();
$(this).val("");
});
$('input').blur(function() {
$(this).val(placeholderText);
});
you still need to do something with the data that is entered.
Upvotes: 0
Reputation: 1549
This will at least get the removal of text working:
var placeholderText = $('input');
placeholderText.focus(function() {
$(this).attr('value', "");
});
placeholderText.blur(function() {
$(this).attr('value', phTextVal);
});
You could also take a look at the HTML5 placeholder param.
Upvotes: 0