Created
February 13, 2013 20:50
-
-
Save micah1701/4948125 to your computer and use it in GitHub Desktop.
Use jQuery to dynamically add "placeholder" text in form inputs that do not support the HTML5 "placeholder" attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="text" placeholder="sample text"> | |
<script> | |
function hasPlaceholder() | |
{ | |
var psuedoInput = document.createElement("input"); | |
return "placeholder" in psuedoInput | |
} | |
$(document).ready(function(){ | |
if(!hasPlaceholder()) | |
{ | |
$("input").each(function(){ | |
input = $(this); | |
if( input.attr('placeholder') != 'undefined' && input.attr('placeholder')) | |
{ | |
var placeholderTxt = input.attr('placeholder'); | |
if($.trim($(this).val()) == '') | |
{ | |
input.val(placeholderTxt); // on load, give it placeholder value | |
} | |
input.on('focus',function(){ | |
if( $(this).val() == placeholderTxt) | |
{ | |
$(this).val(''); | |
} | |
}) | |
.on('blur',function(){ | |
if( $.trim($(this).val()) == '') | |
{ | |
$(this).val(placeholderTxt); | |
} | |
}); | |
} | |
}); // end each through all inputs | |
// when a form is submitted, remove any placeholder text | |
$("form").submit(function(){ | |
$("input").each(function(){ | |
input = $(this); | |
if( input.attr('placeholder') != 'undefined' && input.attr('placeholder') && $(this).val() == input.attr('placeholder') ) | |
{ | |
$(this).val(''); | |
} | |
}); | |
}); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment