I use jQuery Validation plugin to validate my form. My problem is the place of error message for checkbox. please see this image:
I added a class
to the label
for your question in order to find that easier...
<label class="question">What are your favourite genres of movies?<span>*</span></label>
Then you simply need to practice your "DOM traversal" techniques. Study the methods here.
$(element).parents('div')
finds the div
container of your element
.
Then .prev($('.question'))
gets you to the .question
that is the first previous sibling of this div
.
Put it all together and it inserts the error message right after the question.
error.insertAfter($(element).parents('div').prev($('.question')))
Within errorPlacement
:
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.insertAfter($(element).parents('div').prev($('.question')));
} else {
// something else if it's not a checkbox
}
}
DEMO: http://jsfiddle.net/sgsvtd6y/
Maybe you don't need the conditional, since that technique should work on all of your input
types.
errorPlacement: function (error, element) {
error.insertAfter($(element).parents('div').prev($('.question')));
}
Otherwise, if your HTML is different, then you can use the conditional with a slightly modified DOM traversal.