views:

147

answers:

1

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  A: 

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.

Nick Craver
Now the form doesn't submit at all...? The hidden element is removed, however, so I know the `submitHandler` is being called.
neezer
@neezer - Does the form have an action? Or are you trying to submit via ajax?
Nick Craver
@nick It has an action. I want a normal submit, not an Ajax submit.
neezer
@neezer - Are you getting a JavaScript error of any sort?
Nick Craver
@nick Nope, no errors. The submit button just does nothing.
neezer
@neezer - do you have a link to the page I can see?
Nick Craver
neezer
@nick - Of course, as soon as I post the link I can't reproduce the problem. Looks like it works. Thanks.
neezer
@neezer - it happens :) glad you got it working!
Nick Craver