I have a textfield for which change events are bound to a function that validates the textfield's value and may splice a corresponding validation error message into the DOM above the textfield. If the change event is triggered by clicking one of a pair of somewhat unrelated radio buttons, the radio button that is clicked gains the focus but, against my and users' expectations, does not become checked - this is the problem.
Although the validation in the final system will be carried out server-side using AJAX, the following code demonstrates that AJAX has nothing to do with the problem.
Can you tell me what I'm missing here:
<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>