Get label for input field

寵の児 提交于 2019-12-01 03:17:57

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

try to alert

alert($label.text()) 

because you are sending an object to the alert function, if you want to get the content of the selected label you have to get it's html http://jsfiddle.net/s7pYX/2/

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

 $element = $(this)

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

 alert($label)    

 }

 });  

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.

Check this DEMO

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

        $element = $(this);

        var label = $element.closest("div").find("label").text();

        alert(label)

    }

});

This isn't a great example but you could use the prev function from jQuery which will find the previous label before your selected component.

$(document).ready( function() {

   $('input').each(function(){
       alert($(this).prev("label").html())
   });

});

JSFiddle: http://jsfiddle.net/gQnaM/

 var response = ""; 
 $('input').each(function(){
     if ($(this).val() == '') {

     response += ", " + $('label[for="' + this.id + '"]').html();
     }
 }); 

alert(response.replace(", ", "You need to fill out: "));

With JQuery, you can find all the labels linked to the input with $(input).labels();

$('input').each( function() {
    var $labels = $(this).labels();
    $labels.each(function(index, element){
        alert($(element));
    });
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!