jQuery Validation plugin errorPlacement for checkbox

北慕城南 提交于 2019-11-28 00:52:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!