HTML5 Placeholder Fallback using jQuery

If you are a bleeding edge developer chances are you are taking advantage of the new placeholder attribute that can be used with form elements. It can be used on text, textarea, search, url, tel, email, and password fields. One thing to ensure is that older browsers function similarly to ensure consistency and proper user experience. The following snippet can be ran to test for placeholder support, fallback older browsers, and ensure default values are not submitted in those older browsers.

$(document).ready(function() {

	// HTML5 placeholder fallback
	if ( !('placeholder' in document.createElement('input')) ) {
		$("'[placeholder]'").each(function() {
			var val = $(this).attr('placeholder');
			if ( this.value == "" ) {
				this.value = val;
			}
			$(this).focus(function() {
				if ( this.value == val ) {
					this.value = "";
				}
			}).blur(function() {
				if ( $.trim(this.value) == "" ) {
					this.value = val;
				}
			})
		});

		// Clear default placeholder values on form submit
		$('form').submit(function() {
            $(this).find("'[placeholder]'").each(function() {
                if ( this.value == $(this).attr('placeholder') ) {
                    this.value = "";
                }
            });
        });
	}
});

This entry was posted in form, HTML5, input, JavaScript, jQuery, placeholder, Syndicated. Bookmark the permalink.

Comments are closed.