Skip to content

Instantly share code, notes, and snippets.

@carwin
Created October 30, 2012 03:33
Show Gist options
  • Save carwin/3978156 to your computer and use it in GitHub Desktop.
Save carwin/3978156 to your computer and use it in GitHub Desktop.
Drupal 7: HTML5 placeholder attributes for form items with typical jQuery fallback for older browsers.
(function ($) {
Drupal.behaviors.yourTheme = {
attach: function(context, settings) {
$('form label').css('display', 'none');
if(Modernizr.input.placeholder) {
// Text inputs
var formElements = $('form').find('input, textarea');
$.each(formElements, function(index, value){
if($(this).is('input')){
var label = $(this).siblings('label').text();
}else{
var label = $(this).parent().siblings('label').text();
}
$(this).attr('placeholder', label);
});
}else{
var formElements = $('form').find('input, textarea');
$.each(formElements, function(index, value) {
if($(this).is('input')){
var label = $(this).siblings('label').text();
}else{
var label = $(this).parent().siblings('label').text();
}
$(this)
.val(label)
.focus(function(){
if($(this).val(label)) {
$(this).val('');
}
})
.blur(function(){
if(!$(this).val()) {
$(this).val(label);
}
});
});
}
}
}
})(jQuery)
@elgrincho
Copy link

this works perfect for text-fields and text-areas. My problem is, that your script also hides labels from checkboxes and radio-buttons, which makes them unusable!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment