2013-09-25 22 views
1

我在表單中有一些HTML代碼,我需要檢查required="required"屬性的字段是否爲空。相當多的HTML代碼如下所示:通過必需屬性驗證輸入元素並獲得每個輸入的標籤文本

<div class="p_name"> 
    <label class="required" for="product_name">Name</label> 
    <input type="text" maxlength="50" required="required" name="product[name]" id="product_name"> 
</div> 

我建立這個代碼:

$('input[required="required"]').each(function() { 
    if ($(this).val().length === 0) { 
     // Here I should get the text of the label element for 
     // each input and write in the alert but don't know how 
     alert(); 
    } 
}); 

表單元素被一些部門元素與id包裹例如#product-create-step-3所以基於什麼部分元素是我應該只檢查活動部分中的字段,可以給我一些幫助,因爲我不知道如何獲得標籤文本?

回答

1

jsFiddle Demo

的前一個同級
$('input[required="required"]').each(function() { 
    if ($(this).val().length === 0) { 
     var lbl = $(this).siblings('label'); 
     //or var lbl = $(this).prev('label'); 
     alert(lbl.text()); 
    } 
}); 
3

如果您的所有領域的HTML結構是一樣的,你已經發布,你可以使用,.prev()

$('input[required="required"]').each(function() { 
    if ($(this).val().length === 0) { 
     alert($(this).prev('label').text() + ' is required...'); 
    } 
}); 
0

可以使用.prev()選擇與.text()一起提取文本,因爲label元素是輸入元件的問題

$('input[required="required"]').each(function() { 
    if ($(this).val().length === 0) { 
     // Here I should get the text of the label element for 
     // each input and write in the alert but don't know how 
     alert($(this).prev().text() + ' cannot be blank'); 
    } 
}); 
相關問題