繁体   English   中英

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

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

我在表单中有一些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 section元素包装,例如#product-create-step-3所以基于哪些section元素我应该只查看活动部分中的字段,可以给我一些关于这段代码的帮助,因为我不知道获取如何获取标签文本?

如果所有字段的HTML结构与您发布的相同,则可以使用.prev()

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

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

你可以使用.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