How to support placeholder attribute in IE8 and 9
Asked Answered
C

14

132

I have a small issue, the placeholder attribute for input boxes is not supported in IE 8-9.

What is the best way to make this support in my project (ASP Net). I am using jQuery. Need I use some other external tools for it?

Is http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html a good solution?

Curitiba answered 22/2, 2013 at 9:30 Comment(8)
Pedant's corner: it's an attribute, not a tag. A tag has pointy brackets around it (like <input>); an attribute is a key-value pair inside the pointy-brackets (like placeholder="This is an attribute value"). Leaving the question as-is, so that future people who ask the same question can find it.Milburn
That link didn't work as-is. I removed the extra quotes around the $("[placeholder]") selector and it was fine.Poppied
The solution in that link also does not handle password boxes as per native support in webkitFamine
The link you gave works very well indeed - apart from passwords it works a treat and couldn't be simpler to setupWakeless
the link is not working with IE9 by the demo given in same site.Ormand
The link is not a great fix. If you use the required attribute then Firefox will highlight the field in red thinking the user has typed nothing in it.Mid
Link is not working for IE9..Insectivore
The solution in the linked article in combination with a conditional comment is a great solution for most problems: <!--[if lt IE 10]>. Only fix what's broken.Silurian
R
89

You could use this jQuery plugin: https://github.com/mathiasbynens/jquery-placeholder

But your link seems to be also a good solution.

Recall answered 22/2, 2013 at 9:32 Comment(5)
The link suggested in the question didn't work for me; it had problems with form submit. The solution you have suggested in this answer seems a lot more robust and worked a treat.Threnody
Actually I tried this one and is works fine - but as soon as I'm loading a lightbox with a form and a password field, everything works but not the password field - it's just empty.Tolerant
in my IE8 password placeholder is in dotsTrio
I also can't see it in ie8. I worked around it by just having some text show above the fields when in ie8.Extravascular
jQuery-placeholder behaves differently. It removes the placeholder on focus instead of when the user begins typing something on the field like the normal behavior in Firefox for placeholders.Librium
B
89

You can use any one of these polyfills:

These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!

Butyrate answered 22/2, 2013 at 9:51 Comment(12)
I upvoted this because I love the idea of a non-jquery solution, but right now this code has problems in IE8 so it's not suitable for me. github.com/jamesallardice/Placeholders.js/issues/17Dealing
This solution does not handle password boxesTolerant
@Tolerant I have added an extra polyfill - I hope it helps.Butyrate
Even the distributor of this plugin says that this plugin doesn't handle password fields in <IE9 github.com/jamesallardice/Placeholders.js/issues/…Tolerant
The password field still doesn't work in iE8. The accepted answer link seems to work in ie8 for password field.Excreta
@Excreta I added this answer as an alternative to the answers that are already here, just in case someone does not want to use jQuery. If I find a pure javascript polyfill that supports the password field, I will update this answer.Butyrate
"any one of these polyfills" - both these links are to the same library.Octave
@Octave I didn't notice :D I will change that now.Butyrate
After using placeholder.js its not firing required validator in IE9. Any workaround for it ?Insectivore
@vivek Is this your issue? github.com/jamesallardice/Placeholders.js/issues/63Butyrate
I'm trying jamesallardice's Placeholders.js and it seems coolDingman
Polyfills behaves differently. It removes the placeholder on focus instead of when the user begins typing something on the field like the normal behavior in Firefox for placeholders.Librium
D
24

the $.Browser.msie is not on the latest JQuery anymore... you have to use the $.support

like below:

 <script>

     (function ($) {
         $.support.placeholder = ('placeholder' in document.createElement('input'));
     })(jQuery);


     //fix for IE7 and IE8
     $(function () {
         if (!$.support.placeholder) {
             $("[placeholder]").focus(function () {
                 if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
             }).blur(function () {
                 if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
             }).blur();

             $("[placeholder]").parents("form").submit(function () {
                 $(this).find('[placeholder]').each(function() {
                     if ($(this).val() == $(this).attr("placeholder")) {
                         $(this).val("");
                     }
                 });
             });
         }
     });
 </script>
Dinsmore answered 7/2, 2014 at 20:50 Comment(3)
this works like a charm, I like it better than adding plugins, thanks alotWamsley
@vsync no if you read well I said plugins, plural, most of options I've found you need to use multiple files, with tons of code, vs few line. aren't you a bit arrogant, and how doe that comment improve the answerWamsley
This shouldn't really be used. This is for jQuery internal use and could be removed at any time. api.jquery.com/category/deprecated/deprecated-1.9Chide
S
3

if you use jquery you can do like this. from this site Placeholder with Jquery

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

these are the alternate links

  1. Placeholder jquery library
  2. HTML5 polyfills -- go for placeholder section
Sauternes answered 22/2, 2013 at 9:38 Comment(3)
This answer works, but you need to follow the link for the complete functionality. The code here alone won't work.Humfrey
ofc it won't work, this is a ridicules code! why do you bind again and again the same "form" for the submit event? what does the submit event has to do with anythingDarrin
what will happen , if I type same text as in placeholder text in IE8 ???Scandic
H
3

I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:

function placeholders(){
    //On Focus
    $(":text").focus(function(){
        //Check to see if the user has modified the input, if not then remove the placeholder text
        if($(this).val() == $(this).attr("placeholder")){
            $(this).val("");
        }
    });

    //On Blur
    $(":text").blur(function(){
        //Check to see if the use has modified the input, if not then populate the placeholder back into the input
        if( $(this).val() == ""){
            $(this).val($(this).attr("placeholder"));
        }
    });
}
Hydrometer answered 20/11, 2014 at 3:4 Comment(1)
is it supporting for IE9 ?Insectivore
V
2
$(function(){    
    if($.browser.msie && $.browser.version <= 9){
        $("[placeholder]").focus(function(){
            if($(this).val()==$(this).attr("placeholder")) $(this).val("");
        }).blur(function(){
            if($(this).val()=="") $(this).val($(this).attr("placeholder"));
        }).blur();

        $("[placeholder]").parents("form").submit(function() {
            $(this).find('[placeholder]').each(function() {
                if ($(this).val() == $(this).attr("placeholder")) {
                    $(this).val("");
                }
            })
        });
    }
});

try this

Vault answered 10/12, 2013 at 11:22 Comment(0)
S
1

I use thisone, it's only Javascript.

I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.

You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!

You can use a placeholder in a password input by setting the type of the original password input to text.

Tinker: http://tinker.io/4f7c5/1 - JSfiddle servers are down!

*sorry for my bad english

JAVASCRIPT

function removeValue() {
    document.getElementById('mailcontainer')
        .innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
    document.getElementById('email').focus(); }

HTML

<span id="mailcontainer">
    <input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>
Sports answered 3/7, 2013 at 12:46 Comment(1)
Placeholder should come back if field is empty and focus is lostDetain
W
1

For others landing here. This is what worked for me:

//jquery polyfill for showing place holders in IE9
$('[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('');
        }
    })
});

Just add this in you script.js file. Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

Walloping answered 19/10, 2017 at 10:8 Comment(0)
M
0

Since most solutions uses jQuery or are not this satisfying as I wished it to be I wrote a snippet for myself for mootools.

function fix_placeholder(container){
    if(container == null) container = document.body;

    if(!('placeholder' in document.createElement('input'))){

        var inputs = container.getElements('input');
        Array.each(inputs, function(input){

            var type = input.get('type');

            if(type == 'text' || type == 'password'){

                var placeholder = input.get('placeholder');
                input.set('value', placeholder);
                input.addClass('__placeholder');

                if(!input.hasEvent('focus', placeholder_focus)){
                    input.addEvent('focus', placeholder_focus);
                }

                if(!input.hasEvent('blur', placeholder_blur)){
                    input.addEvent('blur', placeholder_blur);
                }

            }

        });

    }
}

function placeholder_focus(){

    var input = $(this);    

    if(input.get('class').contains('__placeholder') || input.get('value') == ''){
        input.removeClass('__placeholder');
        input.set('value', '');
    }

}

function placeholder_blur(){

    var input = $(this);    

    if(input.get('value') == ''){
        input.addClass('__placeholder');
        input.set('value', input.get('placeholder'));
    }

}

I confess that it looks a bit more MORE than others but it works fine. __placeholder is a ccs-class to make the color of the placeholder text fancy.

I used the fix_placeholder in window.addEvent('domready', ... and for any additinally added code like popups.

Hope you like it.

Kind regards.

Muhammad answered 22/5, 2014 at 12:44 Comment(0)
A
0

I used the code of this link http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html

But in browser detection I used:

if (navigator.userAgent.indexOf('MSIE') > -1) {
 //Your placeholder support code here...
}
Anissa answered 28/8, 2014 at 22:15 Comment(0)
R
0
<input type="text" name="Name" value="Name" onfocus="this.value = ''" onblur=" if(this.value = '') { value = 'Name'}" />
Rattray answered 26/1, 2015 at 17:43 Comment(0)
K
0

Add the below code and it will be done.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
    <script type="text/javascript">
        // Mock client code for testing purpose
        $(function(){
            // Client should be able to add another change event to the textfield
            $("input[name='input1']").blur(function(){ alert("Custom event triggered."); });    
            // Client should be able to set the field's styles, without affecting place holder
            $("textarea[name='input4']").css("color", "red");

            // Initialize placeholder
            $.Placeholder.init();

            // or try initialize with parameter
            //$.Placeholder.init({ color : 'rgb(255, 255, 0)' });

            // call this before form submit if you are submitting by JS
            //$.Placeholder.cleanBeforeSubmit();
        });
    </script>

Download the full code and demo from https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip

Kast answered 21/4, 2015 at 10:24 Comment(0)
E
0

Here is a javascript function that will create placeholders for IE 8 and below and it works for passwords as well:

/* 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>
Ellora answered 5/11, 2015 at 22:46 Comment(0)
F
-1
    <script>
        if ($.browser.msie) {
            $('input[placeholder]').each(function() {

                var input = $(this);

                $(input).val(input.attr('placeholder'));

                $(input).focus(function() {
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });

                $(input).blur(function() {
                    if (input.val() == '' || input.val() == input.attr('placeholder')) {
                        input.val(input.attr('placeholder'));
                    }
                });
            });
        }
        ;
    </script>
Fineable answered 27/1, 2014 at 9:4 Comment(1)
$.browser.msie is no longer supported. Try using feature detection instead.Jedidiah

© 2022 - 2024 — McMap. All rights reserved.