Input placeholders for Internet Explorer
Asked Answered
G

17

183

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.

Gilberte answered 2/4, 2011 at 8:41 Comment(0)
E
154

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.

Edam answered 29/8, 2011 at 3:36 Comment(7)
Worked nicely for me in IE7, IE8, and IE9.Wallow
That plugin isn't maintained anymore, and has a lot of known issues.Firenze
Downvote? Answer contained a link to other shims. Updated to include a non-jQuery one.Edam
The github page of plugin isn't exists anymore. Here is another one.Martinet
@KevinHakanson +1 solution working fine in IE,after adding this plugin the placeholder text are left aligned i want it to be in center how to set the placeholder center align.Babbitt
@KevinHakanson After using this placeholder(in demo) is working fine in ie,but if their is any error in form,while displaying the form error the placeholder text gets misaligned from input field,i tried to solve but not able to do.Can you guide me how to solve.Typo
Not too big of a fan that causes the input to be modified, I recommend looking at Nick's answer below. it uses a transparent overlay rather than modifying the value of the inputWedded
S
39

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.

Seizing answered 27/3, 2012 at 21:27 Comment(2)
+1 to this over the jQuery-html5-placeholder. This looks a lot nicer and handles some edge cases missed by the other one (e.g. hidden fields)Knobkerrie
Got to say that this time StackOverflow provided a bad advice. jQuery Placeholder doesn't clear up the input when you click in IE.Soothsayer
S
13

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();
      });
  });
} 
Shirlyshiroma answered 2/4, 2011 at 8:42 Comment(2)
Could you please create a fiddle/demo for the above,will help me and future viewer also.Babbitt
Does it supports for password field.Typo
S
6

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.

Soothsayer answered 18/4, 2013 at 5:16 Comment(2)
After using this placeholder is working fine in ie,but if their is any error in form,while displaying the form error the placeholder text gets misaligned from input field,i tried to solve but not able to do.Can you guide me how to solve.Typo
I really like this one better than the value modifying versions. I wish the html5 version of place holders worked this way as well! (i.e. leaving the placeholder until some text is entered, rather than loosing the value on focus)Wedded
W
4
  • 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('');
        }
      });
    });
  }
});
Woody answered 18/1, 2012 at 6:24 Comment(1)
Many users still use IE8 and some even use IE7. So i wouldn't go for this if it doesn't support themIdiocrasy
M
4

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 :)');
Macegan answered 24/11, 2012 at 21:22 Comment(0)
Y
2

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

Yves answered 1/9, 2011 at 17:55 Comment(1)
This one overrides for all so it will work for all browsers irrespective of IE,WebKit or OperaSmoot
M
2

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);
Mellette answered 28/8, 2013 at 12:5 Comment(0)
K
2

Simple like this:

$(function() {
    ...

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

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

    ...
});
Kalakalaazar answered 5/1, 2017 at 16:35 Comment(0)
N
1

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/

Navarrette answered 31/10, 2011 at 19:53 Comment(1)
seems to work nicely and is very very simple... why only two upvotes?Wisent
C
1

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');
            }
        });
    });
});
Clubwoman answered 18/6, 2013 at 2:21 Comment(1)
perfect salution, but you have an error (this).attr('tooltip', $(this).attr('placeholder')); //buffer change this line to $(this).attr('tooltip', $(this).attr('placeholder')); //bufferKilocycle
T
0

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.

Tacket answered 30/7, 2013 at 10:43 Comment(0)
S
0

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.

Selfmortification answered 13/1, 2014 at 14:33 Comment(2)
@Niclas IE9 and above has it's own native support for placeholders.Hospitalet
I've added a note to this answer with a link to caniuse for placeholders.Selfmortification
S
0

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 won’t run in this case, since it’s 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>
Sheeb answered 29/1, 2015 at 13:51 Comment(0)
H
0

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>
Honeysucker answered 19/11, 2015 at 7:23 Comment(0)
A
-1

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.

Already answered 23/9, 2013 at 14:27 Comment(0)
C
-1

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/

Camilacamile answered 11/11, 2013 at 1:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.