Input placeholders for Internet Explorer

JavascriptHtmlInternet ExplorerPlaceholder

Javascript Problem Overview


HTML5 introduced the placeholder attribute on input elements, which allows to display a greyed-out default text.

Sadly the Internet Explorer, including IE 9 does not support it.

There already are some placeholder simulator scripts out there. They typically work by putting the default-text into the input field, give it a grey color and remove it again as soon as you focus the input field.

The drawback of this approach is that the placeholder text is in the input field. Thus:

  1. scripts can't easily check whether an input field is empty
  2. server side processing must check against the default value, in order to not insert the placeholder into the database.

I would like to have a solution, where the placeholder text isn't in the input itself.

Javascript Solutions


Solution 1 - Javascript

In looking at the "Web Forms : input placeholder" section of HTML5 Cross Browser Polyfills, one I saw was jQuery-html5-placeholder.

I tried the demo out with IE9, and it looks like it wraps your <input> with a span and overlays a label with the placeholder text.

<label>Text:
  <span style="position: relative;">
    <input id="placeholder1314588474481" name="text" maxLength="6" type="text" placeholder="Hi Mom">
    <label style="font: 0.75em/normal sans-serif; left: 5px; top: 3px; width: 147px; height: 15px; color: rgb(186, 186, 186); position: absolute; overflow-x: hidden; font-size-adjust: none; font-stretch: normal;" for="placeholder1314588474481">Hi Mom</label>
  </span>
</label>

There are also other shims there, but I didn't look at them all. One of them, Placeholders.js, advertises itself as "No dependencies (so no need to include jQuery, unlike most placeholder polyfill scripts)."

Edit: For those more interested in "how" that "what", How to create an advanced HTML5 placeholder polyfill which walks through the process of creating a jQuery plugin that does this.

Also, see keep placeholder on focus in IE10 for comments on how placeholder text disappears on focus with IE10, which differs from Firefox and Chrome. Not sure if there is a solution for this problem.

Solution 2 - Javascript

Best one in my experience is https://github.com/mathiasbynens/jquery-placeholder (recommended by html5please.com). http://afarkas.github.com/webshim/demos/index.html also has a good solution among its much more extensive library of polyfills.

Solution 3 - Javascript

With a jQuery implementation you can EASILY remove the default values when it is time to submit. Below is an example:

$('#submit').click(function(){
   var text = this.attr('placeholder');
   var inputvalue = this.val();  // you need to collect this anyways
   if (text === inputvalue) inputvalue = "";

   // $.ajax(...  // do your ajax thing here

});

I know that you are looking for an overlay, but you might prefer the ease of this route (now knowing what I wrote above). If so, then I wrote this for my own projects and it works really nice (requires jQuery) and takes just a couple minutes to implement for your entire site. It offers grey text at first, light grey when in focus, and black when typing. It also offers the placeholder text whenever the input field is empty.

First set up your form and include your placeholder attributes on the input tags.

<input placeholder="enter your email here">

Just copy this code and save it as placeholder.js.

(function( $ ){

   $.fn.placeHolder = function() {  
      var input = this;
      var text = input.attr('placeholder');  // make sure you have your placeholder attributes completed for each input field
	  if (text) input.val(text).css({ color:'grey' });
	  input.focus(function(){  
	     if (input.val() === text) input.css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){     
            input.val("").css({ color:'black' });  
         });
	  });
	  input.blur(function(){ 
	     if (input.val() == "" || input.val() === text) input.val(text).css({ color:'grey' }); 
	  }); 
	  input.keyup(function(){ 
	    if (input.val() == "") input.val(text).css({ color:'lightGrey' }).selectRange(0,0).one('keydown', function(){
			input.val("").css({ color:'black' });
	    });		     	  
      });
      input.mouseup(function(){
	    if (input.val() === text) input.selectRange(0,0); 
	  }); 	
   };
 
   $.fn.selectRange = function(start, end) {
      return this.each(function() {
        if (this.setSelectionRange) { this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
          	var range = this.createTextRange();
	        range.collapse(true); 
		    range.moveEnd('character', end); 
		    range.moveStart('character', start); 
		    range.select(); 
        }
      });
   };

})( jQuery );

To use on just one input

$('#myinput').placeHolder();  // just one

This is how I recommend you implement it on all input fields on your site when the browser does not support HTML5 placeholder attributes:

var placeholder = 'placeholder' in document.createElement('input');  
if (!placeholder) {      
  $.getScript("../js/placeholder.js", function() {   
      $(":input").each(function(){   // this will work for all input fields
        $(this).placeHolder();
      });
  });
} 

Solution 4 - Javascript

After trying some suggestions and seeing issues in IE here is the one that works:

https://github.com/parndt/jquery-html5-placeholder-shim/

What I have liked - you just include the js file. No need to initiate it or anything.

Solution 5 - Javascript

  • Works only for IE9+

The following solution binds to input text elements with the placeholder attribute. It emulates a placeholder behaviour just for IE and clears the input's value field on submit if it is not changed.

Add this script and IE would seem to support HTML5 placeholders.

  $(function() {
  //Run this script only for IE
  if (navigator.appName === "Microsoft Internet Explorer") {
    $("input[type=text]").each(function() {
      var p;
     // Run this script only for input field with placeholder attribute
      if (p = $(this).attr('placeholder')) {
      // Input field's value attribute gets the placeholder value.
        $(this).val(p);
        $(this).css('color', 'gray');
        // On selecting the field, if value is the same as placeholder, it should become blank
        $(this).focus(function() {
          if (p === $(this).val()) {
            return $(this).val('');
          }
        });
         // On exiting field, if value is blank, it should be assigned the value of placeholder
        $(this).blur(function() {
          if ($(this).val() === '') {
            return $(this).val(p);
          }
        });
      }
    });
    $("input[type=password]").each(function() {
      var e_id, p;
      if (p = $(this).attr('placeholder')) {
        e_id = $(this).attr('id');
        // change input type so that the text is displayed
        document.getElementById(e_id).type = 'text';
        $(this).val(p);
        $(this).focus(function() {
          // change input type so that password is not displayed
          document.getElementById(e_id).type = 'password';
          if (p === $(this).val()) {
            return $(this).val('');
          }
        });
        $(this).blur(function() {
          if ($(this).val() === '') {
            document.getElementById(e_id).type = 'text';
            $(this).val(p);
          }
        });
      }
    });
    $('form').submit(function() {
      //Interrupt submission to blank out input fields with placeholder values
      $("input[type=text]").each(function() {
        if ($(this).val() === $(this).attr('placeholder')) {
          $(this).val('');
        }
      });
     $("input[type=password]").each(function() {
        if ($(this).val() === $(this).attr('placeholder')) {
           $(this).val('');
        }
      });
    });
  }
});

Solution 6 - Javascript

I suggest you a simple function :

function bindInOut(element,value)
{
	element.focus(function()
	{
		if(element.val() == value) element.val('');			
	}).
	blur(function()
	{
		if(element.val() == '') element.val(value);
	});
	
	element.blur();
}

And to use it, call it in this way :

bindInOut($('#input'),'Here your value :)');

Solution 7 - Javascript

I found a quite simple solution using this method:

http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

it's a jquery hack, and it worked perfectly on my projects

Solution 8 - Javascript

You can use :

var placeholder = 'search  here';

$('#search').focus(function(){
    if ($.trim($(this).val()) ===  placeholder){
        this.value ='';
    }
}).blur(function(){
    if ($.trim($(this).val()) ===  ''){
        this.value = placeholder;
    }
}).val(placeholder);

Solution 9 - Javascript

Simple like this:

$(function() {
    ...
    
    var element = $("#selecter")
    if(element.val() === element.attr("placeholder"){

        element.text("").select().blur();
    }

    ...
});

Solution 10 - Javascript

I have written a jquery plugin to solve this problem.. it's free..

JQuery Directory:

http://plugins.jquery.com/project/kegles-jquery-placeholder

Site: www.kegles.com.br/jquery-placeholder/

Solution 11 - Javascript

I came up with a simple placeholder JQuery script that allows a custom color and uses a different behavior of clearing inputs when focused. It replaces the default placeholder in Firefox and Chrome and adds support for IE8.

// placeholder script IE8, Chrome, Firefox
// usage: <input type="text" placeholder="some str" />
$(function () { 
    var textColor = '#777777'; //custom color

    $('[placeholder]').each(function() {
        (this).attr('tooltip', $(this).attr('placeholder')); //buffer

        if ($(this).val() === '' || $(this).val() === $(this).attr('placeholder')) {
            $(this).css('color', textColor).css('font-style','italic');
            $(this).val($(this).attr('placeholder')); //IE8 compatibility
        }

        $(this).attr('placeholder',''); //disable default behavior

        $(this).on('focus', function() {
            if ($(this).val() === $(this).attr('tooltip')) {
                $(this).val('');
            }
        });

        $(this).on('keydown', function() {
            $(this).css('font-style','normal').css('color','#000');
        });

        $(this).on('blur', function() {
            if ($(this).val()  === '') {
                $(this).val($(this).attr('tooltip')).css('color', textColor).css('font-style','italic');
            }
        });
    });
});

Solution 12 - Javascript

Placeholdr is a super-lightweight drop-in placeholder jQuery polyfill that I wrote. It's less than 1 KB minified.

I made sure that this library addresses both of your concerns:

  1. Placeholdr extends the jQuery $.fn.val() function to prevent unexpected return values when text is present in input fields as a result of Placeholdr. So if you stick with the jQuery API for accessing your fields' values, you won't need to change a thing.

  2. Placeholdr listens for form submits, and it removes the placeholder text from fields so that the server simply sees an empty value.

Again, my goal with Placeholdr is to provide a simple drop-in solution to the placeholder issue. Let me know on Github if there's anything else you'd be interested in having Placeholdr support.

Solution 13 - Javascript

NOTE: the author of this polyfill claims it "works in pretty much any browser you can imagine" but according to the comments that's not true for IE11, however IE11 has native support, as do most modern browsers

Placeholders.js is the best placeholder polyfill I've seen, is lightweight, doesn't depend on JQuery, covers other older browsers (not just IE), and has options for hide-on-input and run-once placeholders.

Solution 14 - Javascript

TO insert the plugin and check the ie is perfectly workedjquery.placeholder.js

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<script src="jquery.placeholder.js"></script>
	<script>
		// To test the @id toggling on password inputs in browsers that don’t support changing an input’s @type dynamically (e.g. Firefox 3.6 or IE), uncomment this:
		// $.fn.hide = function() { return this; }
		// Then uncomment the last rule in the <style> element (in the <head>).
		$(function() {
			// Invoke the plugin
			$('input, textarea').placeholder({customClass:'my-placeholder'});
			// That’s it, really.
			// Now display a message if the browser supports placeholder natively
			var html;
			if ($.fn.placeholder.input && $.fn.placeholder.textarea) {
				html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> and <code>textarea</code> elements.</strong> The plugin wont run in this case, since its not needed. If you want to test the plugin, use an older browser ;)';
			} else if ($.fn.placeholder.input) {
				html = '<strong>Your current browser natively supports <code>placeholder</code> for <code>input</code> elements, but not for <code>textarea</code> elements.</strong> The plugin will only do its thang on the <code>textarea</code>s.';
			}
			if (html) {
				$('<p class="note">' + html + '</p>').insertAfter('form');
			}
		});
	</script>

Solution 15 - Javascript

Here is a pure javascript function (no jquery needed) that will create placeholders for IE 8 and below and it works for passwords as well. It reads the HTML5 placeholder attribute and creates a span element behind the form element and makes the form element background transparent:

/* Function to add placeholders to form elements on IE 8 and below */
function add_placeholders(fm) {	
	for (var e = 0; e < document.fm.elements.length; e++) {
		if (fm.elements[e].placeholder != undefined &&
		document.createElement("input").placeholder == undefined) { // IE 8 and below					
			fm.elements[e].style.background = "transparent";
			var el = document.createElement("span");
			el.innerHTML = fm.elements[e].placeholder;
			el.style.position = "absolute";
			el.style.padding = "2px;";
			el.style.zIndex = "-1";
			el.style.color = "#999999";
			fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
			fm.elements[e].onfocus = function() {
					this.style.background = "yellow";	
			}
			fm.elements[e].onblur = function() {
				if (this.value == "") this.style.background = "transparent";
				else this.style.background = "white";	
			}		
		} 
	}
}

add_placeholders(document.getElementById('fm'))

<form id="fm">
  <input type="text" name="email" placeholder="Email">
  <input type="password" name="password" placeholder="Password">
  <textarea name="description" placeholder="Description"></textarea>
</form>

Solution 16 - Javascript

i use jquery.placeholderlabels. It's based on this and can be demoed here.

works in ie7, ie8, ie9.

behavior mimics current firefox and chrome behavior - where the the "placeholder" text remains visible on focus and only disappears once something is typed in the field.

Solution 17 - Javascript

I created my own jQuery plugin after becoming frustrated that the existing shims would hide the placeholder on focus, which creates an inferior user experience and also does not match how Firefox, Chrome and Safari handle it. This is especially the case if you want an input to be focused when a page or popup first loads, while still showing the placeholder until text is entered.

https://github.com/nspady/jquery-placeholder-labels/

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
QuestionNikiCView Question on Stackoverflow
Solution 1 - JavascriptKevin HakansonView Answer on Stackoverflow
Solution 2 - Javascriptuser161642View Answer on Stackoverflow
Solution 3 - JavascriptJonathan TongeView Answer on Stackoverflow
Solution 4 - JavascriptfiredevView Answer on Stackoverflow
Solution 5 - JavascriptAlexView Answer on Stackoverflow
Solution 6 - JavascriptAlphaView Answer on Stackoverflow
Solution 7 - JavascriptbluantinooView Answer on Stackoverflow
Solution 8 - JavascriptRoy M JView Answer on Stackoverflow
Solution 9 - JavascriptYitzchok GlanczView Answer on Stackoverflow
Solution 10 - JavascriptNataniel KeglesView Answer on Stackoverflow
Solution 11 - JavascriptmbokilView Answer on Stackoverflow
Solution 12 - JavascriptsffcView Answer on Stackoverflow
Solution 13 - JavascriptDave EverittView Answer on Stackoverflow
Solution 14 - JavascriptSenthamizhmani.SView Answer on Stackoverflow
Solution 15 - JavascriptJeff BakerView Answer on Stackoverflow
Solution 16 - JavascriptJaffadogView Answer on Stackoverflow
Solution 17 - JavascriptnspadyView Answer on Stackoverflow