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/
ありがとうございました。