Get label for input field

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

提交回复
热议问题