Use JavaScript (using jQuery) to add support for HTML5 placeholder attribute in form fields

Some browsers do not support the placeholder attribute added in HTML5. This attribute is useful for field hinting such as input formats for dates, phone numbers, and the like. If you see text in the field below, your browser supports placeholder, if not, add the code below to mimic the behavior 😉

Example field:

JavaScript (jQuery) workaround:

$(function() {
	if (!('placeholder' in document.createElement('input'))) {
		$('form [placeholder]').focus(function(){
			if ($(this).val() == $(this).attr('placeholder')) {
				$(this).val('');
			}
		}).blur(function(){
			if ($(this).val() == '') {
				$(this).val($(this).attr('placeholder'));
			}
		}).blur();
	}
});

Happy coding 😀

2 thoughts on “Use JavaScript (using jQuery) to add support for HTML5 placeholder attribute in form fields

  1. Robert Mullaney Post author

    The code to handle removing the placeholder values prior to submitting…

    $('form').submit(function() {
    $('[placeholder]', this).each(function() {
    if ($(this).val() == $(this).attr('placeholder')) {
    $(this).val('');
    }
    });
    });

    Reply
  2. Robert Mullaney Post author

    A quick note about useability… try to avoid using placeholder as a field label. This should be viewed more like a tool-tip. To my knowledge, screen readers for the visually impaired do not read this attribute aloud.

    Reply

Leave a Reply

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