Placeholder in IE9
Solution 1
HTML5 Placeholder jQuery Plugin
- by Mathias Bynens (a collaborator on HTML5 Boilerplate and jsPerf)
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
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
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
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
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: "/>
![chriscatfr](https://i.stack.imgur.com/TFo2b.jpg?s=256&g=1)
chriscatfr
If they can't figure out how to make call with their phone, they think the phone is useless. If they can't figure out how to do something on their computer, most people think they are themselves useless. I want to provide better tools, so people can focus on their job. They don't need to learn IT Skills if they are the best in their job.
Updated on May 23, 2020Comments
-
chriscatfr about 4 years
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 theinput
andtextarea
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. -
Sami Samhuri over 12 yearsIt works, but it's not the greatest code. At the top
$(this)
should be assigned to a variable which can be used throughout the code. Calling$
for every expression that uses$(this)
is a no-no straight out of "Don't Write jQuery Like This 101". -
ericbae over 12 yearsYou have to be careful with this code since if you submit the form, the placeholder value will be submitted as a form value. Should clear it before it gets submitted.
-
forste over 11 yearsdoesn't work on IE8 since IE does not allow jQuery to manipulate input types (check out comment from Bill on December 20, 2011 at 1:48 pm on bavotasan.com/2011/html5-placeholder-jquery-fix)
-
Snekse over 11 yearsCurious since I'm new to the HTML 5 features battle: Is it modernizer that causes this to be a bad solution or the jquery-html5-placeholder-fix itself (or both)?
-
Leeish over 11 yearsWe are working with a custom CRM. I added this code and the works as expected, but they submit their forms via javascript. The submit button has
onclick="_IW.FormsRuntime.submit(this.form);"
. Is there anyway I can change this onclick event to first clear the placeholders, and then run this CRM code that exists in the onclick? -
rosswil about 11 yearsThis plugin requires the prototype library also
-
eselk about 11 yearsDidn't test it myself, but guessing this doesn't work well if you tab to the field instead of click it. I see this bug in a lot of websites, or ones like it.
-
chovy about 11 yearsalso assumes you are submitting a form. Most Single page apps i've seen do not use forms. just click handlers.
-
Philo over 10 yearsi copied the github js file into my src code. Still no go with the placeholder.
-
smets.kevin over 10 yearsThis indeed works a treat, however it's a pain to use on single page applications. You need to trigger it manually for dynamically added fields. Other than that, works great!
-
Mark Rhodes over 10 yearsSorry - I really don't know if that's easy to do - I guess you'd want to display the actual text value, rather than the "symbols". The only hack I can think of to do this would be to switch it for a text input unless it has focus or a value, otherwise display it as a password field.
-
tjfo over 10 years@smets.kevin What do you mean by you need to trigger it manually? I have an issue where even using the plugin my placeholders are still loading as "null" until I delete null out and then the correct placeholder appears when the input loses focus. I have tried using the jquery id to call the placeholder() function and still can not get it to work...
-
gerrytan about 10 yearsThanks, neat plugin, however one problem I have is with ie9 the placeholder disappears when the text input is on focus. This is different than HTML5 behavior
-
Danubian Sailor about 10 yearsIt works nice with one big 'but', $('input').val() returns the placeholder value when the input is empty. Because I'm working with AJAX framework, that placeholders are sent to server...
-
Chev about 10 years@StephenPatten Have a look at my fix for placeholders with password fields. I do exactly what Mark suggested :)
-
Darren Shewry almost 10 yearsyou should fix your formatting here, like add indentation and separate your answer from your code
-
chriscatfr over 9 yearsyour Placeholder becomes the value. If you submit they will be sent. With the placeholder.js of the correct answer, fields are kept empty
-
Ch Faizan Mustansar over 9 yearsI am using this plugin but it is giving me place holder value when I use jquery val() function, where as on site it says that I can use jquery.val funtion and I should not get the value of the placeholder. Can anyone enlighten this fact and let me know?
-
Igor Jerosimić over 9 yearsWith this solution you also need to check for this value on form submit.
-
LocalPCGuy about 9 yearsI am surprised this got any votes, this should not be used even when posted in 2012/2013
-
Brent about 9 yearsUpdated link which fixes issues in above comments kamikazemusic.com/web-development/…
-
Brent about 9 yearsNote requires Modernizer script with HTML Input features
-
philzelnar almost 9 yearsIf this one doesn't fit your needs, you can find several alternatives in the Modernizr polyfill listing.
-
Spock almost 9 yearsAll these solutions using jQuery..is there no solution without the bloated jQuery?
-
chriscatfr over 8 yearsYou have to be careful with this code since if you submit the form, the placeholder value will be submitted as a form value. You should clear it before it gets submitted.
-
Daniel over 8 yearsIf you happen to write into the input what should be the placeholder ('CV2: ') what you typed will be deleted.
-
Sajjan Sarkar about 8 years@DanglingPointer I think they fixed that, it works for me now wit the .val() too
-
Lain about 8 years@chriscatfr: How would one do that properly in this example? If my placeholder is 'Password' and my password actually is 'Password'?
-
oooyaya about 8 yearsYou could use the concept of "dirty" for fields like this. Flag the field as clean upon entry (maybe use data-dirty="false"). If they submit the form without changing the placeholder text, you'll see that the field is clean, so clear it. If they did change it, even to the same value as the placeholder, then it's dirty and you do submit that value.
-
Shirish Patel about 8 yearsfor the password and other solution please look at the jsfiddle.net/AlexanderPatel/1pv2174c/3
-
jave.web over 7 yearsFor @Philo and others ... This plugin is a tool not a an autorunner, therefore if you'd peaked into README, you would see you have to then use it in your own JS:
$('input, textarea').placeholder();
-
jave.web over 7 yearsDid you test this in IE9 ? Because otherwise IE10+ supports placeholder...
-
jave.web over 7 years
placeholder
property was standardized as string => no need for Modernizr actually:::::::::::::::::::::::::::::if( typeof $('<input type="text">').get(0).placeholder == "undefined" ){ ... }
is enaugh test for not-supporting, tested in IE9 mode emulation - works. -
jave.web over 7 yearsAlso, performance speaking, you should first select subset by fast selector, and filter that by attribute selector and possibly add textarea too:
$('input').filter('[type="text"]').add('textarea')
-
jave.web over 7 yearsLastly, what if an element does not have any placeholder? The final set should be filtered as
.filter('[placeholder]')
-
jave.web over 7 yearsOf course, it's just strange, that IE9 does not support it itself that a tag would turn it on - was it an experimental feature backthen? Is this referenced somewhere? :)