mathiasbynens / jquery-placeholder Goto Github PK
View Code? Open in Web Editor NEWA jQuery plugin that enables HTML5 placeholder behavior for browsers that aren’t trying hard enough yet
Home Page: https://mths.be/placeholder
License: MIT License
A jQuery plugin that enables HTML5 placeholder behavior for browsers that aren’t trying hard enough yet
Home Page: https://mths.be/placeholder
License: MIT License
I have a few fields that are "interactive" and return text from a javascript function. The text that is returned still has the placeholder class (aka, its still gray).
For example I have javascript popup calendar and when a user selects a date it fills in the input field with the selected date, its just gray.
Also, I have another field that is for a "time (hh:mm:ss)", the user can manually enter the time or click a "Now" button which will execute a javascript function and return the current time. Again, the time is filled into the input field but the text remains gray.
Seems overkill, but apparently people want it: http://twitter.com/cheeaun/status/116040426955350016
If you set the value of an input programmatically using $('input').val('something')
the value changes as expected but it still has the placeholder class. Likewise, if you set $('input').val('')
the placeholder should appear again.
I'm not sure the best way of doing this... overwriting jQuery.fn.val
didn't feel clean to me. jQuery also has jQuery.valHooks
which seem like a pretty good way of doing this, but I'm not sure of their status as an API for "public consumption" at this point.
Here's the basic structure of how I'd go about it. I've also included a getter to return the real value to the user rather than the placeholder when it is applied which was my other problem with this plugin.
jQuery.valHooks.input = jQuery.valHooks.textarea = {
set: function(input, value) {
// do something...
},
get: function(input) {
// return real value (not placeholder)
}
}
Thanks for your work on this!
Devon
Placeholder doesnt behave well with IE 7 textareas.
Demo : http://mathiasbynens.be/demo/placeholder (IE7)
In IE8, if you navigate away from a page with placeholders, the field values aren't cleared. If you then come back using the back button, the fields have the placeholder values as real field values.
Changing the event on line 39 from 'unload.placeholder' to 'beforeunload.placeholder' fixes this.
(Only tested on Windows Server 2003 in IE8, Chrome 13, FF 3.6)
It appears this is only a Firefox issue but in my form only the last input is being cleared if the placeholder text equals the value of the field. I'm not entering anything in any of the fields and only the last one is cleared. removing the call to focus()
on line 25 fixes the problem for me. Not sure if I need the field to be focused to on submit.
Other attempts at giving browsers placeholder
abilities can have problems with autocomplete, such as in Firefox.
Does this plugin place nicely with browsers auto-filling values?
When I load a form that has pre-existing values (say a form to edit the user's information), the placeholder is over-riding the existing data and replacing it on non-supported browsers. Is there a way to prevent this client-side? Our only way around this seems to be creating alternative versions of the form fields, one with the placeholder if there is no current data, and one without if there is, which is pretty messy.
I know it's a developer preview (so, unfinished), but I thought I'd give you a heads up anyway: This plugin isn't working in IE10 on the new Windows 8 Developer Preview, which uses the new Metro-style input fields. Instead every field shows "undefined", and doesn't clear when activated. It happens in both the "Metro" (full-screen) and "Desktop" flavors of IE10, which both seem to use the new fields.
I had the same problem with your plugin, and the same fix worked.
"
Submit handler that is added to forms to clear placeholder values is bind only to forms existing in HTML. Any dynamically created forms (for example added with AJAX) don't have it.
A quick fix would be to use delegate
instead of bind
.
So this line:
$('form').bind('submit.placeholder', function() {
would become:
$(document).delegate('form', 'submit.placeholder', function() {
"
A cached page. Navigated back and got the blur event. Since the input value != "" then $input.removeClass('placeholder'); was called.
I put an easy check around if value != $input.attr('placeholder') as in our application it was extremely unlikely that the placeholder text would end up being actually entered.
Here's a jsFiddle I set up to show you this bug:
http://jsfiddle.net/ricksuggs/4NLjJ/1/
When used with jquery-mobile, the styling around the password field stays in the active state after focus is moved from the password field back to the username field.
I haven't tested this extensively, cause I don't have all the browsers on me now, but here's the deal - if you use placeholder text for password/username fields, the results sometimes become unpredictable when the users choose to save their passwords.
All tests performed with a simplified demo.html - removed all fields but the text and password, and gave the text field name="username" (to trigger saving passwords). To trigger the "save password?" on Chrome, demo must submit to a different location (not to self).
Steps to reproduce in most cases:
Results:
O10.63@Ubuntu, O11a@W2K8: the "password" field doesn't have the indicator (yellow inside border) - not a biggie. Hitting ctrl+enter to fill in the form fills in the details, but "placeholder" class is not removed - not a biggie.
IE8@W7, IE9@W2K8: focus into username field, select username from autocomplete dropdown - the password placeholder text still displays, as if the password wasn't filled in. Focus into the password field - the saved password is retrieved OK. Not a biggie - pretty much like Opera.
FF3.6.12@Ubuntu, FF3.6.12@W2K8: for some reason, the "saved username" contains the placeholder of the password (is it because of the unnamed fake password field?) - problematic - could be a bug in FF itself, but the users don't know that, right?...
FF4b7@W2K8, Cr7@W2K8, Cr8@Ubuntu: support placeholder natively.
I didn't test it right now, but the problem becomes even worse if you have multiple usernames/passwords saved for the same form - also, not sure how common that is in real life.
I'm afraid I can't really offer a solution for this - especially considering that some browsers don't report the value for autocompleted password fields (if I remember correctly, having had these issues in a similar implementation a while back).
In practice, I've so far avoided using placeholders for password fields.
Side issue: there may be issues with IE6/7 (I think) maintaining the focus of the fields after hitting "Back" (or was it F5?) - the field is focused, but the focus event is never fired, so the placeholder is inserted. Probably also worth testing this with "autofocus" (where supported).
Applying .placeholder() on an element multiple times should have no effect. Currently it stops working if applied more than once.
I added a quick fix that unbinds every handler before attaching it again.
http://www.pokret.org/files/jquery-placeholder/jquery.placeholder.js
Maybe should be useful to execute the placeholder behaviour for dynamic content added
$(document).live("DOMNodeInserted", "form", function(e){
$(this).find("input, textarea").placeholder();
})
Not tested
In cases where the plugin creates a duplicate input
element to handle password inputs, the id
attribute is copied as well. There should never be two elements with the same id
attribute in the same document. We should toggle the id
attribute between both elements in these cases.
placeholder values are getting submitted with forms. This does not feel like the right behavior.
The behavior of .placeholder() on submit focuses any empty field and cancels the submission. Looking at the source, this seems intentional (and likely done as a shortcut to prevent having to empty out the fields). However, this behavior makes it impossible to have optional fields with placeholders.
There are certain navigation scenarios that can cause placeholder to fail. The following is an example.
<!DOCTYPE html>
<html>
<head>
<style>.placeholder { background-color:yellow; }</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.placeholder.js"></script>
<script type="text/javascript">
if (window.location.search != '') { window.history.back(); }
$(function(){
$('input[placeholder]').placeholder();
$('#submit_link').click(function(){ $(this).closest('form').submit(); });
});
</script>
</head>
<body>
<form action="#submitted" method="get">
Text1: <input type="text" name="txt1" placeholder="text holder"></input><br />
<a href="#submit" id="submit_link">SUBMIT</a>
</form>
</body>
</html>
To see the bug, put this in a directory index file, and click on SUBMIT while the placeholder is displayed (submits form to same file with get parameters "?txt1="). This example automatically navigates "back" after the form submit, and the bug is seen.
You can also see this bug by removing the "window.history.back();" line and manually using the browser's back button.
Look here:
I had no idea where else to submit this and i didn't find any info about this, but it seems Chrome is not clearing placeholder text when field gets focused.
I have tested all browsers that are available to me on browserstack.com and also Chromium and Firefox on Linux Mint.
Results:
Will try to submit this as WebKit bug...
.placeholder definitions for text color, for example, are ignored in FF4 but work in Safari. I am also using jquery 1.5.2 if that raises any issues.
$('input').val('')
sets the values to "undefined"
(when placeholder isn't natively supported, e.g. IE), even if .placeholder()
is never invoked.
Test case:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.placeholder.js"></script>
<script type="text/javascript">
$(function(){
$('form').submit(function(event){
event.preventDefault();
$('input').val('');
});
});
</script>
</head>
<body>
<form>
Text: <input type="text" name="txt"></input><br />
Email: <input type="email" name="eml"></input><br />
Password: <input type="password" name="pwd"></input><br />
<input type="submit" name="sbmt" value="test" />
</form>
</body>
</html>
</pre>
Thank you for sharing this wonderful library. This is the best library available to display place holders.We are using this library along with ASP.net MVC application to display place holders. We come across one issue while working on Html forms , along with Unobtrusive Java scripton on IE7. If the HTML form is Empty and if some of the fields are mandatory, when we submit the form with out entering the mandatory fields, Unobtrusive Jscript wont allow you the post back to the server as mandatory fields validation failed and the first field Value which retains the focus is being overridden by Place holder value.
In order to reproduce the issue, please use the following test cases.
1)Create HTML form with Unobtrusive java script validation in it. Ex: Empty employee form with first name and surname fields as mandatory(i.e.data-val-required="The LasttName field is required.")
Thanks and Regards,
Naveen
When the form contains radio buttons and one of them is checked, refreshing the page will change which radio button is checked (checked state will cycle through all radio buttons) in Firefox 3.6 and 3.5 (and possibly earlier versions).
Demo:
http://taimar.ee/temp/placeholder/demo-radios.html
Radio buttons outside the form element are not affected.
The plugin is missing back/forward support in Opera. To reproduce, open the demo page, submit, and then hit the Back button.
IE 7 & 8
When adding a placeholder on a text field that also has a datepicker, the style doesn't clear properly on the first date selection. Only once a date has been picked and you open the datepicker a second time is the text back to normal.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Datepicker Test</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/ui-lightness/jquery-ui.css" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js" ></script>
<script type="text/javascript" src="https://raw.github.com/mathiasbynens/Placeholder-jQuery-Plugin/master/jquery.placeholder.min.js" ></script>
<style type="text/css">
.placeholder
{
color:#AAA;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.placeholder();
});
</script>
</head>
<body>
<input type="text" id="datepicker" placeholder="This is placeholder" />
</body>
</html>
This code deletes the input element after creating it:
$('#foo').append($('<input type="text">').placeholder());
Here's a live example -- try it with IE9: http://jsfiddle.net/jTnc3/6/
(Minor, whiny request)
The plugin currently says it's version 1.8.2, but there have been multiple Git revisions in that version.
Would you mind doing some kind of formal versioning, maybe by using git tags or something?
Great work, btw. :)
I was hoping to clear the value out of a textarea with: $('#text_form').val(''); and have the placeholder assigned to that element return; however, the box stays blank until I tab in and then out. Is there some way to trigger it back in? I tried to use focus() to go in and out, but no success.
Use the .attributes
collection instead of parsing the HTML using regex (for type=password
in IE).
Something like this should work:
function args($elem) {
var elAttrs = $elem[0].attributes,
newAttrs = {},
i = elAttrs.length;
while (i--) {
newAttrs[elAttrs[i].name] = elAttrs[i].value;
}
return newAttrs;
}
Not sure if the problem lies with Placeholder or with Validate but when a field is invalid and gets focussed to the placeholder breaks.
Uploaded an example here:
http://www.friendly-stranger.com/projects/placeholder/
Occurs in IE6, IE7, IE8 and IE9.
Strangely, your demo site works fine, but uploaded github source doesn't work neither in local file system nor on my server:
http://taimar.ee/temp/placeholder/demo.html
input[type="password"] is the only field that’s NOT affected.
Commit 593350d broketh IE7 and IE6 support. The offending code is $replacement = $('<input>').attr($.extend(args($input[0]), { type: 'text' }))
in the catch(e)
block.
The readme states that the second feature test is cached as jQuery.fn.placeholder.placeholder
, but it should be jQuery.fn.placeholder.textarea
.
In IE, calling .val('') on an input field can break the placeholder functionality, depending on when the .val('') is actually called.
The following code demonstrates the bug.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.placeholder.js"></script>
<script type="text/javascript">
$(function(){
$('input').placeholder();
$('input').keydown(function(event){
if (event.which === 13) {
event.preventDefault(); // Silences bell, but not needed to demonstrate bug.
$(this).val('');
}
});
});
</script>
</head>
<body>
<form>
Text: <input type="text" name="txt" placeholder="text holder"></input><br />
Email: <input type="email" name="eml" placeholder="email holder"></input><br />
Password: <input type="password" name="pwd" placeholder="password holder"></input><br />
</form>
<p>Press Enter in a Text or Email field to see the bug (in IE 9).</p>
</body>
</html>
To get the placeholder plugin to work with IE8 and input type="password"
, you will need to have a id
attribute set. Otherwise, the whole input box disappears when selected.
[11:33:12] <krijn> Matjas' plugin werkt ook niet met met live submits
[11:34:56] <krijn> $('.field').placeholder(); en later $('form').live('submit', function(e) {…… e.preventDefault();})
[11:35:15] <krijn> (<input type="text" class="field" placeholder="fuu">)
[11:35:31] <krijn> Dat submit de placeholder tekst wel
Placeholder plugin isnt working with CKEditor it inserts the placeholder text but doesnt remove it when focused ,
Any solution ?
Hi,
That would be good to trim user input on blur and display the default placeholder even if the user only typed whitespaces. It would behave more "naturally".
HTML part:
`
CSS part:
#search_general input[type="search"] { -webkit-appearance: none; border: 2px solid #f7a708; color: #999; font-weight: bold; padding: 0.3125em; width: 16.25em; font-size: 1em; margin: 0; }
When "-webkit-appearance: none" is added to the CSS-code, the placeholder-value completely disappears from all IE browsers.
In the setPlaceholder function, when the replacement field is created for the password field, the name attribute is removed from the replacement field. In IE7 at least, any input in the form that follows the replacement field is not submitted by the browser to the server. This is in fact causing the password field to not be submitted to the server at all because this replacement field was added to the DOM before the real password field.
$replacement
.removeAttr('name')
// We could just use the `.data(obj)` syntax here, but that wouldn’t work in pre-1.4.3 jQueries
.data('placeholder-password', true)
.data('placeholder-id', id)
.bind('focus.placeholder', clearPlaceholder);
I've fixed this issue for myself by just modifying the name attribute to be something we would never use in a form versus removing the name. For example, I just appended ".replacement" to the name and that solves the issue.
A button with $('button').click(function() { $('form').submit(); return false; });
will fail to clear the placeholder value.
Hello,
Just noticed an issue on IE with your plugin and jquery.validate, indeed, when i had a input type password, and i focused on it, it was saying me instantly that the password was good, even if i had a requirement of 6 characters with the validate plugin.
It was because the value of the input was not empty.
I add a short line in your code in your clearPlaceholder
function , just after the condition
if ($input.val() === $input.attr('placeholder') && $input.hasClass('placeholder')) {
// this is what i add
-> $input.val("");
Tell me if i was wrong to do that, or if you already noticed this problem.
Beside this, your plugin is great, thank you .
I’m sorry to have to say so, but this is a really bad way to implement the PLACEHOLDER attribute in older browsers, because messing around with the VALUE attribute has a significant negative impact on accessibility, and doesn’t work when JS is disabled (no hint/label will be shown at all). Instead of using the VALUE attribute you should use a LABEL element (which has semantic value and is correctly interpreted by assistive technologies) and use JS to float it over the top of the field.
Alas this is one of many jQuery plugins in existence which implement support for PLACEHOLDER in older browsers using this VALUE approach, and there is only one I'm aware of which is fully accessible, semantic, and JS-proof, which is https://github.com/davist11/In-Field-Labels-jQuery-Plugin
It's discussed in detail by the author in his article http://www.viget.com/inspire/a-better-jquery-in-field-label-plugin/ – please read it!
Note also that the WHATWG themselves say "The placeholder attribute should not be used as an alternative to a label." which is another reason why the approach above (using LABEL) is better - see http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-placeholder-attribute
Placeholder grabs the text color of the text, not the natural placeholder color
If the page is able to refresh without destroying form input, then the jquery-placeholder plugin thinks that the original placeholder text is text entered by the user, and so it doesn't add the placeholder class.
Also in this case the original placeholder text will get submitted by the form. For these situations, the jquery plugin really needs to just compare the text against the placeholder text when making its determination, perhaps with an additional toggle option if some users need to be able to enter text that is identical to the placeholder text.
This is not seen on the demo page, because when text is entered into the form on the demo page, and the refresh button is pressed, the entered text is lost. Most browsers will keep form data on most web pages after a refresh (unless the headers disable any caching).
Hello;
In the 'wonderful' ie7 I get an error which Microsoft Script debugger takes me to this chunk
c.focusin(function(){if(c.val()===c.attr('placeholder')){c.val('').removeClass('placeholder')}}).focusout(function(){b(c)})
happy to discuss more and run tests
Hi there,
Just noticed an issue when testing some work on Safari 4 (old version I know, but long story ;)). Looks like Safari 4 supports inputs with placeholder attribute, but not textareas + placeholder.
Because of this, the plugin is currently exiting too early - it finds the input + placeholder support then exits, which means textareas are left alone too.
Not sure if any other browsers have this behaviour, but we've tested a small change on our end (line 8) which seems to do the trick?
if (('placeholder' in document.createElement('input')) && ('placeholder' in document.createElement('textarea'))) {
Win XP - IE6, IE7, IE8, Chrome 7, Firefox 3.6.12
Mac OS - Firefox, Chrome, Safari 4, Safari (latest)
Cheers.
I am doing a validation before submitting and in case validation fails execute event.preventDefault();
When that happens, placeholders no longer work and, in case of password field, if nothing has been entered in it, it remains type="text" on focus.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.