jquery validation when field in DIV with display:none

喜夏-厌秋 提交于 2019-12-13 05:39:22

问题


I got problem on fields with display:none ... I need that after click on submit form button the error message will appear even if the field to validate is in div with display:none setting. I find solution and try to add to the jQuery code setting

ignore: []

but this not change anything. Look at the div with class named 'moreurlinput', he got inline style display:none, but if you change this to display:inline (block,table etc.) the error of validation appear.

html

<form id="post" action="http://m.onet.pl" method="post" class="validatedForm">
<div class="moreurlinput" style="display:none">
    <input class="moreurl center" type="text" name="moreurl" id="moreurl" />
</div>
<div>
    <button type="submit" />Add</button>
</div>
</form>

jquery

jQuery('.validatedForm').validate({
errorElement: "div",
errorClass: 'validate-error',
rules: {
    "moreurl": {
        required: true
    }
},
messages: {
    moreurl: "Please define 'More' URL value"
}

});

HERE: http://jsfiddle.net/Lprn89o8/2/


回答1:


Validation is working exactly as expected. Your whole problem is that the error element is also inside of your hidden div so the message cannot be seen.

The solution is to use the errorPlacement option to place the message outside of your hidden div.

errorPlacement: function(error, element) {
    error.insertAfter($(element).parent());
},

You also need the ignore: [] option so that nothing is ignored and your hidden element is validated.

Working DEMO: http://jsfiddle.net/Lprn89o8/4/


An alternative solution would simply move display:none to the input element, allowing the div to remain visible.

Alternative: http://jsfiddle.net/Lprn89o8/5/


EDIT:

The HTML for your button element is invalid. You should not use a "self-closing" tag since the <button> element itself is a container that has a closing tag.

<button type="submit" />Add</button>

should be...

<button type="submit">Add</button>


来源:https://stackoverflow.com/questions/27871518/jquery-validation-when-field-in-div-with-displaynone

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