jQuery Validation plugin errorPlacement for checkbox

后端 未结 1 1442
长发绾君心
长发绾君心 2020-12-06 17:06

I use jQuery Validation plugin to validate my form. My problem is the place of error message for checkbox. please see this image:

相关标签:
1条回答
  • 2020-12-06 17:08

    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.

    0 讨论(0)
提交回复
热议问题