There is a question form validated by Validation Plugin. It has a lot of fields with checkboxes and radiobuttons, and I want them to be checked after clicking a link with href=”#checkbox-id”.
...
<label class="answer-label" for="answer-2">
<input id="option-2.1" class="answer" type="radio" name="answer-2" value="Yes"/>
<a href="#option-2.1">Yes</a>
</label>
...
Javascript:
$("label.answer-label a").bind("click", function(event) {
event.preventDefault();
var target = $(this).attr("href").replace(".", "\\.");
$(target).click();
} );
Here is validation plugin setup:
$("form#feedback")
.validate({ submitHandler : function ( form ) {
form.submit();
},
errorClass: "invalid",
focusInvalid : false,
debug : true,
invalidHandler : function ( form, validator ) {
var destination = validator.errorList[0].element;
$("html, body").animate({ scrollTop : $(destination).offset().top - 100 });
$(destination).focus();
},
highlight : function ( element, errorClass, validClass ) {
if ( $(element).parents(".name-company") ) {
$(element)
.removeClass(validClass)
.addClass(errorClass);
}
// if ( $(element).parents(".question") ) {
$(element)
.parents(".question")
.removeClass(validClass)
.addClass(errorClass);
// }
},
unhighlight : function ( element, errorClass, validClass ) {
if ( $(element).parents(".name-company") ) {
$(element)
.removeClass(errorClass)
.addClass(validClass);
}
// if ( $(element).parents(".question") ) {
$(element)
.parents(".question")
.removeClass(errorClass)
.addClass(validClass);
// }
},
errorPlacement : function () {
return false;
}
});
The problem is: clicking on label checks the input element, but validation events fire only after the second click.
I found a workaround (or, probably, a correct way to trigger validation events)! The trick is to bind the “change” event on checkboxes and radio button, like this:
This binding must be set before any other “change” event binding, so that every “change” event will trigger the validation check.