Created
January 12, 2012 13:30
-
-
Save gavinblair/1600526 to your computer and use it in GitHub Desktop.
HTML5 placeholder and required for IE9
This file contains hidden or 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
//from http://kamikazemusic.com/quick-tips/jquery-html5-placeholder-fix/#comment-938 | |
$(document).ready(function() { | |
if (Modernizr.input.placeholder) | |
return; | |
$('input[placeholder]').focus(function() { | |
if ($(this).hasClass('placeholder')) { | |
if ($(this).val() == $(this).attr('placeholder')) | |
$(this).val(''); | |
$(this).removeClass('placeholder'); | |
} | |
}); | |
$('input[placeholder]').keypress(function() { | |
if ($(this).hasClass('placeholder')) { | |
if ($(this).val() == $(this).attr('placeholder')) | |
$(this).val(''); | |
$(this).removeClass('placeholder'); | |
} | |
}); | |
$('input[placeholder]').blur(function() { | |
if ($(this).val() != '') | |
return; | |
$(this).addClass('placeholder'); | |
$(this).val($(this).attr('placeholder')); | |
}); | |
$('input[placeholder]').each(function() { | |
if ($(this).val() != '' && $(this).val() != $(this).attr('placeholder')) | |
return; | |
$(this).val($(this).attr('placeholder')).addClass('placeholder'); | |
}); | |
$('form').submit(function() { | |
$(this).find(".placeholder").each(function() { | |
$(this).removeClass('placeholder'); | |
$(this).val(''); | |
}); | |
validateform($(this)); | |
}); | |
}); | |
function validateform(form){ | |
if (Modernizr.input.required) | |
return true; //already handled | |
var valid = true; | |
form.find("input[required]").each(function(){ | |
if($(this).val().length == 0) { | |
valid = false; | |
$(this).addClass('redborder'); | |
} else { | |
$(this).removeClass('redborder'); | |
} | |
}); | |
return valid; | |
} |
todo: add in email validation as well for input type="email"
I added it to the bottom of plugins.js (if you're using html5 boilerplate), otherwise at the bottom of your javascript file. Don't add it to your existing $(document).ready() though. Requires jQuery and Modernizr.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
adapted from http://kamikazemusic.com/quick-tips/jquery-html5-placeholder-fix/#comment-938