Get label for input field
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
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.