I\'m doing a validation with Jquery and need to get the $label from each element with their own label. Now the alert() gives med [object object]. The best thing for me here
try to alert
alert($label.text())
With JQuery, you can find all the labels linked to the input with $(input).labels();
$('input').each( function() {
var $labels = $(this).labels();
$labels.each(function(index, element){
alert($(element));
});
});
This isn't a great example but you could use the prev
function from jQuery which will find the previous label before your selected component.
$(document).ready( function() {
$('input').each(function(){
alert($(this).prev("label").html())
});
});
JSFiddle: http://jsfiddle.net/gQnaM/
Check this DEMO
$('input').each(function () {
if ($(this).val() == '') {
$element = $(this);
var label = $element.closest("div").find("label").text();
alert(label)
}
});
because you are sending an object
to the alert function, if you want to get the content of the selected label you have to get it's html
http://jsfiddle.net/s7pYX/2/
$('input').each(function(){
if ($(this).val() == '') {
$element = $(this)
var $label = $("label[for='"+$element.attr('id')+"']").html();
alert($label)
}
});
var response = "";
$('input').each(function(){
if ($(this).val() == '') {
response += ", " + $('label[for="' + this.id + '"]').html();
}
});
alert(response.replace(", ", "You need to fill out: "));