Created
September 16, 2011 09:50
Picking up label text on input click with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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