0

私はこの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>

required="required"そして、空の値を持つ各要素のアラートを表示しようとしているので、これを作成しました:

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

放置し#product_nameたり#product_description空にしたりすると、アラートが表示されず、見逃したものを見つけることができません。何かアドバイスはありますか?

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ないため、 を含めないでください>。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

No, look at the DOM more closely, the query should be:

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

or:

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

since the > selects elements that are direct children of the parent.

于 2013-09-25T18:41:46.017 に答える