November 13, 2011 in Javascript, Programming, Tutorials by admin

Have you ever wanted a fully compatible way to get placeholder text into your html input fields? Placeholder text can help your users better understand the form field as well as add a bit of dynamic flare to the website. We can do this fairly easily with JavaScript and HTML.

We can accomplish the effect of our placeholder text disappearing and reappearing a few different ways in JavaScript. I will show you how to do this using the jQuery Framework and the placeholder plugin. This really is a great solution and very easy to use.

JQuery Placeholder Text Solution
First we will want to download and include jQuery as well as the placeholder plugin in the header section of our html:

<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<script type="text/javascript" src="js/jquery.placeholder.js"></script>

Next we will add our placeholder attribute to our input fields in our html form:

//The placeholder attribute works in modern browsers
<input type="text" name="firstname" placeholder="First Name" />

The placeholder attribute works in almost all modern browsers, however in some older browsers and even newer versions of Internet Explorer do not recognize it. The placeholder plugin will replicate this functionality on the fly by clearing the text and replacing it when users enter text or leave the field empty.

In order to get this to work all we have to do now is call one line of javascript to instantiate our placeholder plugin which will make the placeholder attribute work across all browsers.