jQuery验证:提交之前在验证之后删除元素? [英] jQuery Validate: Remove element AFTER validation BEFORE submit?
问题描述
我有一个城市的SVG地图,当单击该地图时,会在我的表单中的div中创建隐藏的元素.
I have a SVG map of a city that when clicked, creates hidden elements in a div in my form.
我正在使用 jQuery验证插件来验证我的表单.
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>
但是,我不能将该伪元素与表单的其余部分一起提交;我需要在表单经过验证之后但在提交表单之前将其删除.自然,我想对validate()
使用submitHandler
选项:
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?
推荐答案
submitHandler
需要进行调整,如下所示:
The submitHandler
needs a tweak, like this:
submitHandler: function(form) {
$(form).find('input[name=dummy]').remove();
form.submit();
}
调用jQuery .submit()
触发器会再次导致验证,并且无限循环...您要在此处调用本机 .submit()
函数.
Calling the jQuery .submit()
trigger causes validation again, and an infinite loop...you want to call the native .submit()
function here.
这篇关于jQuery验证:提交之前在验证之后删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!