0

I have this HTML:

<fieldset style="display: block;" title="Producto" class="fstep" id="product-create-step-2">
    <section>
        <div class="p_name">
            <input type="text" maxlength="50" required="required" name="product[name]" id="product_name">
        </div>
        <div class="p_description">
            <textarea required="required" name="product[description]" id="product_description"></textarea>
        </div>
        <div class="p_age">
            <input type="text" value="0" name="product[age_limit]" id="product_age_limit">
        </div>
    </section>
</fieldset>

And I'm trying to show a alert for each element with required="required" with empty values so I made this:

$('#product-create-step-2 > input[required="required"]').each(function() {
    if (!$.trim(this.value).length) {
        alert($(this).prev('label').text() + ' can't be empty!!!');
        valid = false;
    }
});

If I leave #product_name or #product_description empty it never shows a alert and I can't find what I miss, any advice?

4

4 回答 4

5

>用于选择直系后代

你想要这个:

$('#product-create-step-2 input[required="required"]')

#product-create-step-2无论嵌套多深,它都会在 内部找到所有匹配的输入。

此外,这将导致语法错误:

' can't be empty!!!'

您需要转义单引号或切换引号:

' can\'t be empty!!!'

或(我的偏好):

"can't be empty"
于 2013-09-25T18:40:34.600 回答
1

您的元素不是 的直接子元素,#product-create-step-2因此您不应包含>. 只需在两个选择器之间留一个空格,您就可以在#product-create-step-2.

$('#product-create-step-2 input[required="required"]')
于 2013-09-25T18:41:07.043 回答
0

You have no inputs directly underneath the 1st selector.

Try changing your selector to:

$('#product-create-step-2 > section > div > input[required="required"]')

Or even just

$('#product-create-step-2 input[required="required"]')
于 2013-09-25T18:41:24.047 回答
0

不,更仔细地查看 DOM,查询应该是:

$('#product-create-step-2 input[required="required"]').each ...

或者:

$('#product-create-step-2 > section > div > input[required="required"]').each ...

因为>选择的是父元素的直接子元素。

于 2013-09-25T18:41:46.017 回答