テキストフィールドの値を検証する関数に変更イベントがバインドされているテキストフィールドがあり、対応する検証エラーメッセージをテキストフィールドの上の DOM にスプライスする可能性があります。多少無関係なラジオ ボタンのペアのいずれかをクリックして変更イベントがトリガーされた場合、クリックされたラジオ ボタンはフォーカスを取得しますが、私とユーザーの期待に反して、チェックされません。これが問題です。
最終的なシステムでの検証は AJAX を使用してサーバー側で実行されますが、次のコードは、AJAX が問題とは何の関係もないことを示しています。
ここで何が欠けているか教えてください:
<html>
<head>
<STYLE type="text/css">
.highlighted { color: red; }
</STYLE>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<span id="errors">
</span>
<label for="mytextfield">First, type something in this textfield</>
<input type="text" id="mytextfield" name="mytextfield"/>
<p>Second, click on one of these radio buttons</>
<INPUT TYPE="radio" NAME="binaryquestion" VALUE="Y" >Yes</>
<INPUT TYPE="radio" NAME="binaryquestion" VALUE="N" >No</>
<script type="text/javascript">
$(document).ready(function() {
//$("#mytextfield").change(validateTextField);
$("#mytextfield").change(spliceInTheValidationResultMessage);
});
function validateTextField() {
$.ajax({
url: 'http://www.google.com',
success: function(data) {
spliceInTheValidationResultMessage();
}
});
}
function spliceInTheValidationResultMessage() {
$("#errors").append("<p>Thank you for your input!</p>").addClass("highlighted");
alert("I expect the radio button that you clicked to become checked. However, close this dialog and you'll see that it will have gained the focus but is NOT checked!");
};
</script>
</body>
</html>