Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get label for input field

Tags:

jquery

each

label

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"

like image 910
Kim Avatar asked Aug 22 '13 08:08

Kim


People also ask

How do you show the label inside the input field?

There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit). Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.

How can I get element labels?

Use the textContent property to get the text of a label element, e.g. const text = label. textContent . The textContent property will return the text content of the label and its descendants.

What is label for input?

<label>: The Input Label element. The <label> HTML element represents a caption for an item in a user interface.

Is label required for input?

Input fields without accompanying labels can lead to accessibility issues for those who rely on screen readers. If a screen reader comes across an input field without a label it will try to find some accompanying text to use as the label.


1 Answers

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

like image 194
Arun P Johny Avatar answered Nov 13 '22 15:11

Arun P Johny