Placeholder in IE9

JavascriptHtmlInternet Explorer-9Placeholder

Javascript Problem Overview


It seems it's a very well known problem but all the solutions I found on Google don't work on my newly downloaded IE9.

Which is your favorite way in order to enable the Placeholder property on the input and textarea tags?

Optional: I lost a lot of time on that and didn't look for the required property yet. Would you also have some advice for this? Obviously I can check the value in PHP, but to help the user this property is very convenient.

Javascript Solutions


Solution 1 - Javascript

HTML5 Placeholder jQuery Plugin

https://github.com/mathiasbynens/jquery-placeholder

Demo & Examples

http://mathiasbynens.be/demo/placeholder

p.s
I have used this plugin many times and it works a treat. Also it doesn't submit the placeholder text as a value when you submit your form (... a real pain I found with other plugins).

Solution 2 - Javascript

I think this is what you are looking for: jquery-html5-placeholder-fix

This solution uses feature detection (via modernizr) to determine if placeholder is supported. If not, adds support (via jQuery).

Solution 3 - Javascript

If you want to do it without using jquery or modenizer you can use the code below:

(function(){

     "use strict";
     
     //shim for String's trim function..
     function trim(string){
         return string.trim ? string.trim() : string.replace(/^\s+|\s+$/g, "");
     }

     //returns whether the given element has the given class name..
     function hasClassName(element, className){ 
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return false;
         var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
         return regex.test(element.className);
     }
     
     function removeClassName(element, className){
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return;
         element.className = elClassName.replace(
             new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ');
     }

     function addClassName(element, className){
         var elClassName = element.className;
         if(elClassName)
             element.className += " " + className;
         else
             element.className = className;
     }

     //strings to make event attachment x-browser.. 
     var addEvent = document.addEventListener ?
            'addEventListener' : 'attachEvent';
     var eventPrefix = document.addEventListener ? '' : 'on';

     //the class which is added when the placeholder is being used..
     var placeHolderClassName = 'usingPlaceHolder';
     
     //allows the given textField to use it's placeholder attribute
     //as if it's functionality is supported natively..
     window.placeHolder = function(textField){

         //don't do anything if you get it for free..
         if('placeholder' in document.createElement('input'))
             return;

         //don't do anything if the place holder attribute is not
         //defined or is blank..
         var placeHolder = textField.getAttribute('placeholder');        
         if(!placeHolder)
             return;

         //if it's just the empty string do nothing..
         placeHolder = trim(placeHolder);
         if(placeHolder === '')
             return;
         
         //called on blur - sets the value to the place holder if it's empty..
         var onBlur = function(){
             if(textField.value !== '') //a space is a valid input..
                 return;
             textField.value = placeHolder;
             addClassName(textField, placeHolderClassName);
         };

         //the blur event..
         textField[addEvent](eventPrefix + 'blur', onBlur, false);
         
         //the focus event - removes the place holder if required..
         textField[addEvent](eventPrefix + 'focus', function(){
             if(hasClassName(textField, placeHolderClassName)){
                removeClassName(textField, placeHolderClassName);
                textField.value = "";
             }
         }, false);
         
         //the submit event on the form to which it's associated - if the
         //placeholder is attached set the value to be empty..
         var form = textField.form;
         if(form){
             form[addEvent](eventPrefix + 'submit', function(){
                 if(hasClassName(textField, placeHolderClassName))
                     textField.value = '';
            }, false);
         }
         
         onBlur(); //call the onBlur to set it initially..
    };

}());

For each text field you want to use it for you need to run placeHolder(HTMLInputElement), but I guess you can just change that to suit! Also, doing it this way, rather than just on load means that you can make it work for inputs which aren't in the DOM when the page loads.

Note, that this works by applying the class: usingPlaceHolder to the input element, so you can use this to style it (e.g. add the rule .usingPlaceHolder { color: #999; font-style: italic; } to make it look better).

Solution 4 - Javascript

Here is a much better solution. http://bavotasan.com/2011/html5-placeholder-jquery-fix/ I've adopted it a bit to work only with browsers under IE10

<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]><html class="no-js lt-ie10 lt-ie9" lang="en"> <![endif]-->
<!--[if IE 9]><html class="no-js lt-ie10" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]-->
    
    <script>
    // Placeholder fix for IE
      $('.lt-ie10 [placeholder]').focus(function() {
        var i = $(this);
        if(i.val() == i.attr('placeholder')) {
          i.val('').removeClass('placeholder');
          if(i.hasClass('password')) {
            i.removeClass('password');
            this.type='password';
          }     
        }
      }).blur(function() {
        var i = $(this);  
        if(i.val() == '' || i.val() == i.attr('placeholder')) {
          if(this.type=='password') {
            i.addClass('password');
            this.type='text';
          }
          i.addClass('placeholder').val(i.attr('placeholder'));
        }
      }).blur().parents('form').submit(function() {
        //if($(this).validationEngine('validate')) { // If using validationEngine
          $(this).find('[placeholder]').each(function() {
            var i = $(this);
            if(i.val() == i.attr('placeholder'))
              i.val('');
              i.removeClass('placeholder');
    
          })
        //}
      });
    </script>
    ...
    </html>

Solution 5 - Javascript

If you want to input a description you can use this. This works on IE 9 and all other browsers.

<input type="text" onclick="if(this.value=='CVC2: '){this.value='';}" onblur="if(this.value==''){this.value='CVC2: ';}" value="CVC2: "/>

Solution 6 - Javascript

Using mordernizr to detect browsers that are not supporting Placeholder, I created this short code to fix them.

//If placeholder is not supported
if (!Modernizr.input.placeholder){ 

    //Loops on inputs and place the placeholder attribute
    //in the textbox.
    $("input[type=text]").each( function() { 
       $(this).val($(this).attr('placeholder')); 
    })
}

Solution 7 - Javascript

I know I'm late but I found a solution inserting in the head the tag:

<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <!--FIX jQuery INTERNET EXPLORER-->

Solution 8 - Javascript

to make it work in IE-9 use below .it works for me

JQuery need to include:

jQuery(function() {
   jQuery.support.placeholder = false;
   webkit_type = document.createElement('input');
   if('placeholder' in webkit_type) jQuery.support.placeholder = true;});
   $(function() {
 
     if(!$.support.placeholder) {
 
       var active = document.activeElement;
 
       $(':text, textarea, :password').focus(function () {
 
       if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&         ($(this).attr('placeholder') != '') && $(this).val() == $(this).attr('placeholder')) {
          $(this).val('').removeClass('hasPlaceholder');
        }
      }).blur(function () {
if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&  ($(this).attr('placeholder') != '') && ($(this).val() == '' || $(this).val() ==   $(this).attr('placeholder'))) {
     $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
 
$(':text, textarea, :password').blur();
$(active).focus();
$('form').submit(function () {
     $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});

CSS Style need to include:

.hasPlaceholder {color: #aaa;}

Solution 9 - Javascript

A bit late to the party but I use my tried and trusted JS that takes advantage of Modernizr. Can be copy/pasted and applied to any project. Works every time:

// Placeholder fallback
if(!Modernizr.input.placeholder){

	$('[placeholder]').focus(function() {
	  var input = $(this);
	  if (input.val() == input.attr('placeholder')) {
		input.val('');
		input.removeClass('placeholder');
	  }
	}).blur(function() {
	  var input = $(this);
	  if (input.val() == '' || input.val() == input.attr('placeholder')) {
		input.addClass('placeholder');
		input.val(input.attr('placeholder'));
	  }
	}).blur();
	$('[placeholder]').parents('form').submit(function() {
	  $(this).find('[placeholder]').each(function() {
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
		  input.val('');
		}
	  })
	});

}

Solution 10 - Javascript

I usually think fairly highly of http://cdnjs.com/ and they are listing:

//cdnjs.cloudflare.com/ajax/libs/placeholder-shiv/0.2/placeholder-shiv.js

Not sure who's code that is but it looks straightforward:

document.observe('dom:loaded', function(){
  var _test = document.createElement('input');
  if( ! ('placeholder' in _test) ){
    //we are in the presence of a less-capable browser
    $$('*[placeholder]').each(function(elm){
      if($F(elm) == ''){
        var originalColor = elm.getStyle('color');
        var hint = elm.readAttribute('placeholder');
        elm.setStyle('color:gray').setValue(hint);
        elm.observe('focus',function(evt){
          if($F(this) == hint){
            this.clear().setStyle({color: originalColor});
          }
        });
        elm.observe('blur', function(evt){
          if($F(this) == ''){
            this.setValue(hint).setStyle('color:gray');
          }
        });
      }
    }).first().up('form').observe('submit', function(evt){
      evt.stop();
      this.select('*[placeholder]').each(function(elm){
        if($F(elm) == elm.readAttribute('placeholder')) elm.clear();
      });
      this.submit();
    });
  }
});

Solution 11 - Javascript

I searched on the internet and found a simple jquery code to handle this problem. In my side, it was solved and worked on ie 9.

$("input[placeholder]").each(function () {
        var $this = $(this);
        if($this.val() == ""){
            $this.val($this.attr("placeholder")).focus(function(){
                if($this.val() == $this.attr("placeholder")) {
                    $this.val("");
                }
            }).blur(function(){
                if($this.val() == "") {
                    $this.val($this.attr("placeholder"));
                }
            });
        }
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchriscatfrView Question on Stackoverflow
Solution 1 - JavascriptChris JacobView Answer on Stackoverflow
Solution 2 - JavascriptmattView Answer on Stackoverflow
Solution 3 - JavascriptMark RhodesView Answer on Stackoverflow
Solution 4 - JavascriptStanislav PisockijView Answer on Stackoverflow
Solution 5 - JavascriptErdem KAYAView Answer on Stackoverflow
Solution 6 - JavascriptEtienne DupuisView Answer on Stackoverflow
Solution 7 - JavascriptdecadenzaView Answer on Stackoverflow
Solution 8 - JavascriptSuresh GuptaView Answer on Stackoverflow
Solution 9 - Javascriptegr103View Answer on Stackoverflow
Solution 10 - JavascriptcwdView Answer on Stackoverflow
Solution 11 - JavascriptGünay GültekinView Answer on Stackoverflow