jQuery Validate: Remove element AFTER validation BEFORE submit?

偶尔善良 提交于 2019-12-20 05:49:05

问题


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

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