Skip to content

Instantly share code, notes, and snippets.

@makeusabrew
Created May 22, 2011 18:32
Show Gist options
  • Save makeusabrew/985739 to your computer and use it in GitHub Desktop.
Save makeusabrew/985739 to your computer and use it in GitHub Desktop.
Simple jQuery snippet to convert form labels into inline placeholders
$("form :input").each(function(index, elem) {
var eId = $(elem).attr("id");
var label = null;
if (eId && (label = $(elem).parents("form").find("label[for="+eId+"]")).length == 1) {
$(elem).attr("placeholder", $(label).html());
$(label).remove();
}
});
@Mugane
Copy link

Mugane commented Oct 27, 2017

or do $(label).hide(); instead of $(label).remove(); that way it's still there for the screen readers.

@Mugane
Copy link

Mugane commented Oct 27, 2017

Actually you probably want to check if the field is a select and adjust the replacement behavior appropriately (setting the "placeholder" attribute of a select input will not display that text):

$("form :input").each(function(index, elem) {
var eId = $(elem).attr("id");
var label = null;
if (eId && (label = $(elem).parents("form").find("label[for="+eId+"]")).length == 1) {
if($(elem).is("select")) $(elem).prepend("<option value disabled selected hidden>"+$(label).html()+"</option>");
else $(elem).attr("placeholder", $(label).html());
$(label).hide();
}
});

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