Input Element Placeholder Attribute in IE

HTML5 introduced the placeholder attribute for the input tag. However, it doesn’t work in IE 9 and below.

In this tutorial, I will be taking advantage of the fact that  setting the placeholder attribute on an input element can be read as the “value attribute” of that element. So, here is a solution that uses Javascript/Jquery.

IE Placeholder Fix

<input id="searchKey" type="text" name="searchKey" placeholder="Search" />

Here is the javascript:

jQuery(document).ready(function($) {
	var originalValue;
	if($.browser.msie){
		originalValue = $('#searchKey').attr('value');
	}else{
		originalValue = $('#searchKey').attr('placeholder');
	}
	var placeAttr = $('#searchKey').attr('placeholder');

	$('#searchKey').focus(function() {
			$('#searchKey').attr('placeholder', '');
			if($.browser.msie && $('#searchKey').attr('value') == originalValue){
				$('#searchKey').attr('value', ''); 
			}
		});
	$('#searchKey').blur(function(){
		$('#searchKey').attr('placeholder', placeAttr);
		if($.browser.msie && ($('#searchKey').attr('value') == "" || $('#searchKey').attr('value') == originalValue)){
			$('#searchKey').attr('value', originalValue);
		}
	});
});

I’ve tested the placeholder ie fix in IE 9- IE 7 ( firefox and chrome also work).

Input Element Placeholder Attribute Fix Demo

3 comments ↓

#1 jaime on 11.21.12 at 9:18 PM

Here is a more general one as well:
http://html5forwebdesigners.com/forms/index.html#fig-04-01

#2 Cristian B. on 11.26.12 at 4:17 PM

Would be nice to see a demo. :)

#3 Mandeep on 12.06.12 at 4:28 AM

Hi Cristian,

I have added a video that explains the code and provides a demo. Hope it helps.

Thanks

Leave a Comment


7 × = 35

CommentLuv badge