jQuery Input Placeholder Support Check and Replacement

These two go hand in hand. First a small jQuery plugin to check to see if the browser supports the “placeholder” attribute. Then, if not, a bit of Javascript to mimic the effect as a fallback.

Check for support by creating an input element then attempting to get the value from it’s “placeholder” attribute.

// jQuery.placeholder support
// if (!$.support.placeholder)
jQuery.support.placeholder = (function(){
	var i = document.createElement('input');
	return 'placeholder' in i;
})();

// ===============================
// Check for placeholder support
// If not present replace with javascript substitute
// ===============================
var inputText = $('input[type=text]');
var va; // value
var ph; // placeholder
if (!$.support.placeholder) {
	$('input[type=text]').each(function() {
		va = $(this).val();
		ph = $(this).attr('placeholder');
		// if the value is empty, put the placeholder value in it's place
		if (!va || va == '') {
			$(this).val(ph);
		}
	});
	// replaceing the placeholder type effect
	$(inputText).focus(function() {
		va = $(this).val();
		ph = $(this).attr('placeholder');
		if (va == ph) {
			$(this).val('');
		}
	}).blur(function() {
		va = $(this).val();
		ph = $(this).attr('placeholder');
		if (va == '') {
			$(this).val(ph);
		}
	});
}

Select the inputs of type “text” within the page. If placeholders aren’t supported by the browser, go through each of the input elements and fake the effect.

  • Place the value of the placeholder into the “value” attribute
  • On focus, check to see if the value matches the text in the placeholder attribute. If so, clear the value.
  • On blur, check to see if the value is empty. If so, fill the value with the text in the placeholder attribute.

Share

Comments