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 the contents of $label
, you can use .text() for this
$('input').each(function(){
var $element = $(this)
if ($element.val() == '') {
var $label = $("label[for='"+this.id+"']")
alert($label.text())
}
});
Demo: Fiddle
Update
var $labels = $("label[for]");
var empties = $('input').filter(function(){
return $.trim($(this).val()) == ''
}).map(function(){
return $labels.filter('[for="'+this.id+'"]').text()
}).get().join(', ')
alert(empties)
Demo: Fiddle
Instead of below line:
var $label = $("label[for='"+$element.attr('id')+"']"
Use the following code:
var $label = $("label[for='"+$element.attr('id')+"']").text();
You are getting only the object you need to use the .html()
or .text()
to get the text inside the label tag.
Try
$('input').each(function(){
if ($(this).val() == '') {
$element = $(this)
var $label = $("label[for='"+$element.attr('id')+"']")
alert("You need to fill :" + $label.text())
}
});
DEMO
Update :
is it possible to arrange all the $label in one alert() and not one alert() each?
Yes
var errorString ="";
var isNeedToFill=false;
$('input').each(function(){
if ($(this).val() == '') {
isNeedToFill =true;
$element = $(this)
var $label = $("label[for='"+$element.attr('id')+"']");
errorString += $label.text()+" ";
}
});
if(isNeedToFill){
alert("You need to fill :" +errorString);
}
DEMO
Improving upon the answer you could wrap it in a function:
function getLabel(name) {
var $label = $("label[for='" + name + "']")
return ($label.text());
}
var label = getLabel(this.id);
console.log(label);
This makes it much easier to reuse the code.