How To Create A Browser Independent Input Field Placeholder

What is a placeholder?

The placeholder is some text those are shown as filler text for input fields during page load. Once you put focus on the fields the text disappears and on focusing out, the filler text again gets back to the input field, if nothing has been entered.

Do we have something to achieve this?

We do have a placeholder html5 attribute for input fields to create placeholders. But the main problem is using this is this property is not currently supported by all browsers. Hence its not adviseable to use it in your web applications. So for now its not useable for us.

So what is the solution?

We can write our code in javascript/jQuery to achieve this. But again it needs to be as generic as the placeholder attribute, where we just need to set the placeholder text as an attribute in the input field and our job is done. No more look into javascript/jQuery code to set placeholders for different fields.

So here we go with the simplest code to achive the solution for all browsers. Here we will have few lines of jQuery code written, which executes on document ready. And we just need to set our desired placeholder attribute in our input fields and then we are done.

FYI, just to break the conflict among html5 placeholder attribute and mine set attribute, I have named this attribute as “filler”. You can set this attribute “filler” to as many fields as you wish.

//Javascript Code
 
//Set the filler attribute value to all input fields which is having this attribute  

$("[filler]").each(function(index, element) {    

   $(element).val($(element).attr("filler"));

});

 

//On focusing the field clear the text if nothing entered by end user

$("[filler]").live("focusin", function(){   

    if($(this).val() == $(this).attr("filler")){       

         $(this).val("");    

   }

});

 

//On focus out again fill the filler text to the field if nothing entered by end user

$("[filler]").live("focusout", function(){   

    if(!$(this).val().length){      

       $(this).val($(this).attr("filler"));   

    }

});

 

 
150 150 Burnignorance | Where Minds Meet And Sparks Fly!