Get label for input field

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

提交回复
热议问题