Skip to content

Adding a label when placeholder isn’t supported by browser

I’m sitting here working on a JavaScript heavy web app, and it has a few forms that are large enough that the placeholder attribute available in HTML 5 was the way to go. Only catch, not all browsers support placeholder so I needed something to fall back on.

What I normally do is put a label on top of the field, and that seemed a pretty good solution to fallback on if placeholder isn’t supported.

Since I was already loading jQuery and the web app won’t work without JavaScript enabled it’s a good option to use jQuery to add elements to the page. Were I doing this for a public site I probably would go with something else. But since I have a bit more control over those that will be using the app requiring JavaScript is okay.

The code below should be added somewhere in your JavaScript.

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

$(document).ready(function() {
    if (!$.support.placeholder) {
        $.each($('[placeholder]'), function(i, val) {
            $('<p>' + $(this).attr('placeholder') + '</p>').insertBefore(this);
        });
    }
});

The addition to the $.support came from David Walsh with a slight modification to shrink it to one line.

What the code in the .ready function does is check to see if the placeholder attribute is supported. If not, it then goes through and inserts a bit of HTML above the field using the placeholder attribute as the text. For this example it’s just wrapped in paragraph tags. But I’ll probably wind up using a label instead so that it’s clickable.

Screenshots

Sure, why not?

placeholder on Chrome
Placeholder attribute how it should look - in Chrome
placeholder in IE
Placeholder hack in a browser (IE) that doesn't support the attribute

And yes, the Chrome version also is sporting drop shadows and curved corners; neither of which are supported in IE.

Other Options?

The most common solution I came across was to hook onto the focus and blur events of anything with a placeholder attribute. blur() would set the text of the control back to the placeholder if the input field is empty and focus() would blank it out if the text is the same as the placeholder.

I tried a couple of plugins that did this, and none really worked all that well. Each that I tried had an issue where if you clicked in the middle of the text it wouldn’t blank it out.

The other problem is that since the text is getting set, submitting the form would submit the placeholder as well.

The other solution I found put another HTML element on top of the text field. Didn’t try any of those though since it just seemed messier.

Published inProgramming

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *