Skip to content

Instantly share code, notes, and snippets.

@redroot
Created September 16, 2011 09:50
Picking up label text on input click with jQuery
/*
Take a look at the console http://jsbin.com/onipeq/
*/
$("input").live("click",function(){
label = findLabel($(this));
console.log(label);
});
function findLabel(/* jQuery Element */ el){
var label = null;
// lets find a label
var name = el.attr("name");
var using_for = $('label[for="'+name+'"]').text();
if(using_for.length > 0){
label = using_for;
}else{
// cant find it using for so lets try
// find closest
var closest = el.prevAll("label");
if(closest.text().length > 0){
label = $.trim(closest.text());
}else{
closest = $.trim(el.closest("label").text());
label = closest;
}
}
return label;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment