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" value="Search" name="searchKey" placeholder="Search" />

Here is the javascript/jquery:

function placeHolderFix(element){
	var originalValue;
	var is_chrome = window.chrome;
	if(is_chrome){
		$(element).val("");
	}

    if(navigator.appVersion.indexOf("MSIE") !== -1){
            originalValue = $(element).val();
      }else{
            originalValue = $(element).attr('placeholder');
    }


    var placeAttr = $(element).attr('placeholder');
    $(element).focus(function() {
                    $(element).attr('placeholder', '');

                    if(navigator.appVersion.indexOf("MSIE") !== -1 && $(element).val() == originalValue){
                            $(element).val(""); 
                    }
            });
    $(element).blur(function(){
            $(element).attr('placeholder', placeAttr);
            if(navigator.appVersion.indexOf("MSIE") !== -1 && $(element).val() == ""){
                    $(element).attr('value', originalValue);
            }
    });
}
jQuery(document).ready(function($) {
     var searcKey = $("#searchKey");
     placeHolderFix(searcKey);	
});

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

Input Element Placeholder Attribute Fix Demo

  1. Hi,

    Thanks for the information. How about a link to a working demo page that I can test in IE, just to double check my browser. I have copied the provided code verbatim but it doesn’t work for me in IE 9.0.8.

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

*


6 + = 9

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge