简体   繁体   English

按需要的属性验证输入元素,并获取每个输入的标签文本

[英]Validate input element by required attribute and get the label text for each input

I have some HTML code inside a form and I need to check whether fields with required="required" attribute are empty or not. 我在表单中有一些HTML代码,我需要检查具有required="required"属性的字段是否为空。 Pretty much HTML code looks like this: 几乎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>

I'm building this code: 我正在构建此代码:

$('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();
    }
});

Form elements are wrapped by some section element with id for example #product-create-step-3 so based on what section elements are I should check only fields within the active section, can any give me some help on this code since I don't get how to get the label text? 表单元素由一些带有id section元素包装,例如#product-create-step-3所以基于哪些section元素我应该只查看活动部分中的字段,可以给我一些关于这段代码的帮助,因为我不知道获取如何获取标签文本?

If the HTML structure for all your fields is the same as you have posted, you can use, .prev() : 如果所有字段的HTML结构与您发布的相同,则可以使用.prev()

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

jsFiddle Demo jsFiddle演示

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

you can use the .prev() selector along with .text() to extract the text because the label element is the previous sibling of the input element in question 你可以使用.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');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM