Get label for input field

前端 未结 10 554
野趣味
野趣味 2021-01-11 09:53

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

相关标签:
10条回答
  • 2021-01-11 10:16

    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

    0 讨论(0)
  • 2021-01-11 10:18

    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.

    0 讨论(0)
  • 2021-01-11 10:23

    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

    0 讨论(0)
  • 2021-01-11 10:27

    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.

    0 讨论(0)
提交回复
热议问题