HTML5 Placeholder jQuery Fix

I was working with placeholder text for the input fields on a recent project and I needed to make sure that the text would appear in all browsers. I had to use a old technique that many of you might be familiar with:


That technique uses inline JavaScript to check if the value of the input field matches the default placeholder text. It works in every browser but it does require a lot of extra code on each of your input fields. It would also submit the placeholder text as the value of the input so you would have to place some validation to remove any value that matched the placeholder text.
All of those issues are solved in HTML5 with the placeholder parameter. Now your input tag would just look like this:


That does the exact same thing and will not submit a value for the empty input fields.
This HTML5 feature is supported in the following browsers:
Firefox: 3.7+
Safari: 4.0+
Chrome: 4.0+
Opera: 11.0+
iPhone: 4.0+
Since it doesn’t work in IE and older browsers, you need to use something like this jQuery fix:


First thing it does is check whether the placeholder parameter is supported. If it is, it will do nothing. If it isn’t it will perform a few things to emulate the HTML5 placeholder parameter. In order to style how your placeholder text appears you can use the following CSS:

.placeholder {
  color: #aaa;
  }

The fix will also switch the input type to “text” for all password inputs so that your placeholder text will not appear as a bunch of black dots. The final part of the fix will empty the value of the input field if it contains the placeholder text so that it is not submitted as a real value in your form.
Since this is a jQuery fix, you need to make sure that you have included a link to jQuery between your head tags:


With everything in place, you now have a backwards compatible way of using the new HTML5 placeholder parameter so that all of your visitors have the same experience when they are on your site.
Resources:
http://www.webgeekly.com/tutorials/jquery/creating-a-cross-browser-form-field-placeholder/
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie