0

フォームの検証に問題があります。それぞれ 2 つの回答を持つ 2 つの DIV コンテナーがあります。チェックされたラジオが 1 つ以上あるか、1 つのテキスト要素に値があるかを検証したいと思います。

しかし、私のjQueryセレクターは機能しません:

HTML:

<div class="mandatory">
    <input type="radio" value="1" name="answer1" /> Option 1
    <input type="radio" value="2" name="answer1" /> Option 2
</div>

<div class="mandatory">
    <input type="radio" value="1" name="answer2" /> Option 1
    <input type="text" name="answer2" />
</div>

JS:

$('.mandatory').each(function(){
    var elem = $(this).find('input:checked, input:text[value!=""]');
    console.log(elem.attr('name')); //Always "answer2"
});

空ですが、入力要素を返しました。これが私のコードです: http://fiddle.jshell.net/Pisi2012/n9S2Y/

ご協力いただきありがとうございます!

4

4 に答える 4

1

入力には値属性がないため、属性セレクターが一致します。値は空の文字列ではないため、値がありませんか?

変化する

<input type="text" name="answer2" />

<input type="text" name="answer2" value="" />

フィドル

于 2013-07-19T08:18:08.937 に答える
0

このコードを試してください:

$('.mandatory').each(function(){
    var elem = $(this).find('input:checked, input[type="text"][value!=""]');
    console.log(elem.attr('name')); //Always "answer2"
});
于 2013-07-19T08:16:26.790 に答える
0

私が想定しているのはmandatory、指定された条件を満たさないdivのリストが必要であり、試してみることです

var els = $('.mandatory').filter(function(){
    var $this = $(this);

    return !$this.find(':radio:checked').length && !$this.find(':text').filter(function(){return $.trim(this.value) != ""}).length
});

デモ:フィドル

于 2013-07-19T08:33:04.803 に答える