Pierre
Pierre

Reputation: 13046

How to use this JQuery function for clearing input text?

I was trying to clear input text using onfocus and onblur inside the input tag, but I'm going to use it on many fields so I found this JQuery function but I can't seem to make it work.

$('.default-value').each(function() {

   var default_value = this.value;

   $(this).focus(function(){
           if(this.value == default_value) {
                   this.value = '';
           }
   });

   $(this).blur(function(){
           if(this.value == '') {
                   this.value = default_value;
           }
   }); 
});

I tried putting this inside script tag inside the head tag, and I added a class of default-value to the inputs I want to clear but it doesn't work.

so what am I doing wrong ? I don't know javascript and I'm linking to the latest JQuery.

and thanks

Upvotes: 0

Views: 332

Answers (2)

CompanyDroneFromSector7G
CompanyDroneFromSector7G

Reputation: 4527

I don't think this will work because of closure. You need to remember the default value for each field. e.g.

$('.default-value').each(function() {

   $(this).attr('default_value',$(this).val());

   $(this).focus(function(){
       if($(this).val() == $(this).attr('default_value')) {
               $(this).val('');
       }
   });

   $(this).blur(function(){
       if($(this).val() == '') {
               $(this).val($(this).attr('default_value'));
       }
   }); 
});

Upvotes: 2

Mathias Bynens
Mathias Bynens

Reputation: 149734

Seems like you’re re-inventing @placeholder here.

Just use HTML like this:

<input type="text" placeholder="foo bar">

This is supported in most modern browsers.

Then, use a polyfill to make sure older browsers get similar behavior. I’ve written one in jQuery plugin format, if you’re interested: http://mths.be/placeholder

Use it as follows:

$('input, textarea').placeholder();

Here’s a demo: http://mathiasbynens.be/demo/placeholder

Upvotes: 3

Related Questions