Skip to content

Instantly share code, notes, and snippets.

@tombeynon
Created September 6, 2012 10:10
Show Gist options
  • Save tombeynon/3654329 to your computer and use it in GitHub Desktop.
Save tombeynon/3654329 to your computer and use it in GitHub Desktop.
Inline labels
<label class="inline" for="field">Label</label>
<input id="field" name="field" />
function supports_input_placeholder() {
var i = document.createElement('input');
return 'placeholder' in i;
}
$("label.inline").each(function(){
var label = $(this);
var labelText = label.text();
var field = $("#"+label.attr("for"));
// Hide label
$(this).hide();
if(supports_input_placeholder()){
field.attr("placeholder",labelText);
}else{
var form = $(this).closest("form");
// Set label if nothing entered
if(field.val() == "" || field.val() == labelText){
field.val(labelText).addClass("placeholder");
}
// Clear value if label still present
field.bind("focus",function(){
if(field.val() == labelText){
field.val("").removeClass("placeholder");
}
}).bind("blur",function(){
if(field.val() == ""){
field.val(labelText).addClass("placeholder");
}
});
// Clear input on form submit if nothing entered
form.bind("submit",function(){
if(field.val() == labelText){
field.val("");
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment