问题
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?
回答1:
The submitHandler needs a tweak, like this:
submitHandler: function(form) {
$(form).find('input[name=dummy]').remove();
form.submit();
}
Calling the jQuery .submit() trigger causes validation again, and an infinite loop...you want to call the native .submit() function here.
回答2:
This seemed to work for me when the above answer did not. Maybe has to do with jQuery and jQuery Validation versions.
submitHandler: function(form) {
$('input[name=dummy]', form).remove();
form.submit();
}
来源:https://stackoverflow.com/questions/3677858/jquery-validate-remove-element-after-validation-before-submit