Making HTML5 Placeholder Input Fields Cross-Browser with JQuery

Nicholas Cerminara

HTML5 placeholders for inputs allow for a very UI and UX friendly way of supercharging your forms. You can use them to annotate what the form field is or an example of what a correct value would look like.

Note: Placeholders don't necessarily replace the label tag. Some screen readers don't interpret placeholders as labels. If you plan on using the Placeholder tag to label your input field, remember to add a label and hide it with CSS. Bootstrap does this well. Here's an example.

Unfortunately, Internet Explorer 9 and below doesn't support the Placeholder attribute. After scavenging the web for a jQuery cross-browser solution that makes sense, I've come to really like this post on how to fix it. It's ridiculously simple and gets the job done superbly.

In short, this fix works by taking the all input fields with a placeholder attribute and adding it to the value attribute (making it appear on the form). Then on user select, it simply removes it. It goes one step by removing the value on form submit if it is equal to the Placeholder attribute. This means it doesn't submit things like "First Name", "Email", or whatever you have put for your placeholder. Lastly, it also adds a class called placeholder for unique CSS styling.

Here's the code:


$(function() {
    $('[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('');
            }
        })
    });
});