Introduction
HTML5 has introduced many features to the browser; some HTML-based, some in the form of JavaScript APIs, but all of them useful. Among those we have the placeholder attribute, which shows text in a field until the field is focused upon, then hides the text.
In the past this was traditionally implemented using Javascript, but native HTML5 support relieves front-end developers of another stone to carry. As long as the browsers they are working on support it, of course.
The Problem
For those older browsers to whom users stubbornly keep clinging to, there is little choice other than implementing a Javascript solution. In itself this is a simple enough task, as it can be done in just a few lines with a little help from Modernizr:
if (!Modernizr.input.placeholder) { $('[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(); }
This, however, has two unintended side-effects over the native HTML5 solution, specifically:
- It changes the actual value of the affected field, potentially triggering validation;
- A field that is “blank” in appearance is to all intents and purposes containing the placeholder as its actual value; this value will be submitted with the form, if no countermeasures are adopted.
The Solution
Luckily, because elements with placeholders can be identified from their attribute, both the validation and the submission process may be modified to take them into account, since our code differentiates between controls containing a user-specified value or just the default placeholder by means of a CSS class.
Therefore, we can take advantage of JQuery Validation’s ignore option; by virtue of it, elements matching a specific CSS selector it will not trigger validation:
.validate({ ignore: ".placeholder" });
In our case this will include empty elements, as those are automatically reverted to the default placeholder value.
Finally, form submission can be intercepted, and the value of fields with a placeholder reverted to empty to ensure proper validation:
$('[placeholder]').parents('form').submit(function () { $(this).find('[placeholder]').each(function () { var input = $(this); if (input.val() == input.attr('placeholder')) { input.val(''); } }) });
Both of these methods have been field tested and deployed in commercial solutions.
Conclusion
Emulating HTML5 features via Javascript is often a necessity, in an industry where support for older browsers is often a requirement; however all necessary steps must be taken to ensure that our client code does not interfere with the existing environment.