Skip to content

Instantly share code, notes, and snippets.

@micah1701
Created February 13, 2013 20:50
Show Gist options
  • Save micah1701/4948125 to your computer and use it in GitHub Desktop.
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
<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