Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created January 12, 2012 13:30
Show Gist options
  • Save gavinblair/1600526 to your computer and use it in GitHub Desktop.
Save gavinblair/1600526 to your computer and use it in GitHub Desktop.
HTML5 placeholder and required for IE9
//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;
}
@gavinblair
Copy link
Author

@gavinblair
Copy link
Author

todo: add in email validation as well for input type="email"

@gavinblair
Copy link
Author

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