0

x、y、その他の選択肢を持つラジオ ボタン グループがあるとします。ユーザーが x または y を必要としない場合は、その他を選択できます。これにより、テキスト フィールドに独自の値を入力できるようになります。HTML コード:

<input type="radio" name="choice" id="x" value="x"/><label for="x">x</label><div></div>
<input type="radio" name="choice" id="y" value="y"/><label for="y">y</label><div></div>
<input type="radio" name="choice" id="other" value="other"/><label for="other">other </label><input type="text" id="otherText"/><span id="error"></span><div></div>

入力した値が検証されます (数値のみ可能です)。検証には jQuery を使用しています。ユーザーが数字以外を入力すると、エラー メッセージが表示されます。jQuery は、span#error の innerHtml を変更します。ここに私のjQueryコードがあります:

$(document).ready(function() {
$("input#otherText").attr("disabled", "disabled");

$("input:radio").click(function() {
    var choice = $(this).val();
    if(choice != "other") {
        $("input#otherText").attr("disabled", "disabled");
        console.log("Choice " + choice);
    }else {
        $("input#otherText").removeAttr("disabled");
    }
});

$("input#otherText").blur(function() {
    console.log("is Other Checked: " + $("input#other").is(":checked"));

    // If some other radio button is chosen, then I don't want to validate.
    if($("input#other").is(":checked")) {
        $("span#error").html("");
        var otherValue = $.trim(jQuery(this).val());
        if(otherValue != ' ' && otherValue.length > 0) {
            if(!otherValue.match(/^[0-9]+$/)) {
                $("span#error").html(otherValue + " is not a number.");
                $("span#error").css({"font-weight":"bold", "color":"red"});
            }
        }            
    }
});            
});

検証は期待どおりに機能していますが、私の問題はいつ検証するかを決定することです。上記のコードは、ユーザーがテキスト フィールドに値を入力し、クリックまたはタブ アウトしたときに検証します。これは、x や y などの他の無線が選択された場合でも検証が行われることを意味します。そのため、.is(":checked") を other に追加すると、別のラジオが選択されていても true が返されます。クリックされていないのに「その他」が true と評価されるのはなぜですか? 誰かがこれに光を当てることができますか?

これがフィドルの私のコードです: http://jsfiddle.net/9Zycy/

ありがとうございました。

4

2 に答える 2

0

ID付きのラジオがチェックされている場合に検証を回避したい場合otherは、次のようにします

if($("input:radio").not("input[id='other']").is(":checked")) {
  //your validation here
于 2013-05-31T04:51:44.937 に答える
0
var choice = $(this).val();

コード内のこの行は、選択変数に常に「未定義」を返します。value 属性を radio 入力要素に追加します。

<input type="radio" name="choice" id="x" value="x"/><label for="x">x</label><div></div>
<input type="radio" name="choice" id="y" value="y"/><label for="y">y</label><div></div>
<input type="radio" name="choice" id="other" value="other"/><label for="other">other </label><input type="text" id="otherText"/><div></div>

あなたのjqueryコードは私には問題ないようです。しかし、あまり詳しく見ていませんでした。しかし、上記は間違いなく修正が必要です。以下を使用することもできます。

var choice = $(this).attr('id');
于 2013-05-31T04:59:58.303 に答える