jQuery validation of radio buttons with highlighting of labels.
Do not select a radio button, click submit and the "Yes" label is highlighted. Then click "No" and submit and the "Yes" label disappears. Need to fix that and also would like to have both "Yes" and "No" labels highlighted when validation fails.
HTML
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js"></script>
<form id="edit_form" action="" method="post">
<div class="formerror" style="display: none">
<span></span>
</div>
<input type="radio" name="chooseMe" value="Yes" id="radio_yes" /><label for="radio_yes">Yes</label>
<input type="radio" name="chooseMe" value="No" id="radio_no" /><label for="radio_no">No</label>
<br />
<input type="submit" value="submit" />
</form>
CSS
div.formerror
{
color: red;
margin-bottom: 6px;
margin-top: 1px;
}
input.error, select.error, label.error
{
border: 2px solid red;
background-color: #FFFFD5;
margin: 0px;
color: red;
}
JavaScript
$('#edit_form').validate({
rules: {
chooseMe: "required"
},
messages: {
chooseMe: ""
},
highlight: function(element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
$(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass);
$(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
},
submitHandler: function(form) {
$("#edit_form div.formerror").hide();
alert("validated successfully - submit handler here");
},
invalidHandler: function(e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = 'There are missing or invalid fields. They have been highlighted below.';
$("#edit_form div.formerror span").html(message);
$("#edit_form div.formerror").show();
} else {
$("#edit_form div.formerror").hide();
}
}
});