jQuery 验证:在提交之前验证后删除元素?
我有一个城市的 SVG 地图,单击该地图时,会在我的表单中的 div 中创建隐藏元素。
我正在使用 jQuery 验证插件 来验证我的表单。
为了确保用户单击了地图的某个区域,我想在正常隐藏元素所在的位置创建一个虚拟隐藏元素,并在其上放置验证规则。我编写了自己的验证规则来检查隐藏元素的数量(表明用户单击了地图上的某个位置)。该规则是这样的:
$.validator.methods.zones = function (value, element, param) {
return ($('#search_form #zone-selectors input').length > 1); // 1 instead of 0 to account for the dummy element
};
<div id="zone-selectors">
<input type="hidden" name="dummy">
</div>
但是,我不能允许该虚拟元素与表单的其余部分一起提交;我需要在表单验证后但提交表单之前将其删除。自然地,我想使用 validate()
的 submitHandler
选项:
// ...
submitHandler: function(form) {
$(form).find('input[name=dummy]').remove();
$(form).submit();
},
// ...
...但这似乎会创建一个无限循环,并且我的浏览器使脚本超时。我做错了什么?
I have a SVG map of a city that when clicked, creates hidden elements in a div in my form.
I'm using the jQuery Validation Plugin to validate my form.
In order to make sure that the user has clicked on an area of the map, I thought to create a dummy hidden element inside where the normal hidden elements are and put the validation rule on that. I wrote my own validation rule to check for the number of hidden elements (indicating that a user has clicked somewhere on the map). That rule is this:
$.validator.methods.zones = function (value, element, param) {
return ($('#search_form #zone-selectors input').length > 1); // 1 instead of 0 to account for the dummy element
};
<div id="zone-selectors">
<input type="hidden" name="dummy">
</div>
However, I cannot allow that dummy element to be submitted with the rest of the form; I need to remove it AFTER the form has been validated but BEFORE the form is submitted. Naturally, I thought to use the submitHandler
option for validate()
:
// ...
submitHandler: function(form) {
$(form).find('input[name=dummy]').remove();
$(form).submit();
},
// ...
... but this seems to create an infinite loop, and my browser times-out the script. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
submitHandler
需要调整,如下所示:调用 jQuery
.submit( )
触发器再次导致验证,并且无限循环...您想调用本机.submit()
函数在这里。The
submitHandler
needs a tweak, like this:Calling the jQuery
.submit()
trigger causes validation again, and an infinite loop...you want to call the native.submit()
function here.当上面的答案不起作用时,这似乎对我有用。也许与 jQuery 和 jQuery 验证版本有关。
This seemed to work for me when the above answer did not. Maybe has to do with jQuery and jQuery Validation versions.