Get label for input field

前端 未结 10 553
野趣味
野趣味 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:08

    try to alert

    alert($label.text()) 
    
    0 讨论(0)
  • 2021-01-11 10:11

    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));
        });
    });
    
    0 讨论(0)
  • 2021-01-11 10:13

    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/

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

    Check this DEMO

    $('input').each(function () {
        if ($(this).val() == '') {
    
            $element = $(this);
    
            var label = $element.closest("div").find("label").text();
    
            alert(label)
    
        }
    
    });
    
    0 讨论(0)
  • 2021-01-11 10:15

    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)    
    
     }
    
     });  
    
    0 讨论(0)
  • 2021-01-11 10:15
     var response = ""; 
     $('input').each(function(){
         if ($(this).val() == '') {
    
         response += ", " + $('label[for="' + this.id + '"]').html();
         }
     }); 
    
    alert(response.replace(", ", "You need to fill out: "));
    
    0 讨论(0)
提交回复
热议问题