Get label for input field

Kim picture Kim · Aug 22, 2013 · Viewed 57.4k times · Source

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 is to get an alert() with all fields lined up that is not filled out. And not an alert() for each.

Here is a fiddle: http://jsfiddle.net/s7pYX/

How is this accomplished?

HTML:

<div>
<label for="txtName">Name</label>
<input type="text" id="txtName" class="form-control" name="txtName">
</div>

<div>
<label for="txtEmail">E-mail</label>
<input type="text" id="txtEmail" class="form-control" name="txtEmail">
</div>

Jquery:

 $('input').each(function(){
 if ($(this).val() == '') {

 $element = $(this)

 var $label = $("label[for='"+$element.attr('id')+"']")

 alert($label)    

 }

 });  

In the alert() I expect like this "You need to fill out: Name, E-mail"

Answer

Arun P Johny picture Arun P Johny · Aug 22, 2013

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