webdevgirl
webdevgirl

Reputation: 23

how do I clear the values in my text input fields?

My code doesn't run and I want the value to be cleared when you click on another

what am I doing wrong?

http://jsfiddle.net/AL2vS/

var placeholderText = $('input').val();

$(placeholderText).focus(function() {
    $(this).attr('value', "");
});
$(placeholderText).blur(function() {
    $(this).attr('value', phTextVal);
});​

Upvotes: 2

Views: 148

Answers (6)

Blazemonger
Blazemonger

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

Rahen Rangan
Rahen Rangan

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

cbacelar
cbacelar

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

Roger
Roger

Reputation: 7612

Check it out,

$('input').focus(function() {
    placeholderText = $('input').val();
    $(this).val("");
});

$('input').blur(function() {
    $(this).val(placeholderText);
});​

http://jsfiddle.net/AL2vS/8/

you still need to do something with the data that is entered.

Upvotes: 0

clexmond
clexmond

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

aztechy
aztechy

Reputation: 640

Do you mean like this?

http://jsfiddle.net/AL2vS/1/

Upvotes: 0

Related Questions