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"
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.
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.
<label>: The Input Label element. The <label> HTML element represents a caption for an item in a user interface.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With