开发者

Rails 3 Jquery validate plugin

开发者 https://www.devze.com 2023-02-04 00:36 出处:网络
I have this js code $(\".new_milestone\").validate({ submi开发者_如何学CtHandler: function(form) {

I have this js code

$(".new_milestone").validate({
     submi开发者_如何学CtHandler: function(form) {
    $(form).submitWithAjax();
   },
     errorPlacement: function(error, element) {
        error.insertBefore(element);
     }
   });  

It all works, errorPlacement and the submitWithAjax function. But when I post the form the second time without reloading the page, the form gets posted two times. Next time 3 times and so on.

When I do this

 $(".new_milestone").validate({
             errorPlacement: function(error, element) {
                error.insertBefore(element);
             }
           });
$(".new_milestone").submitWithAjax(); 

It works, but it does the ajax post even if the form is not valid.

The submitWithAjax function looks like this (thanks Ryan Bates)

jQuery.fn.submitWithAjax = function() {
  this.submit(function() { 

    $.post(this.action, $(this).serialize(), null, "script");
    $('.spinning').show(); 
    $("#dialog_form").dialog("close")
    return false;
  })
  return this;
};

Any ideas on stopping this behavior?


This is happening because your ssubmitWithAjax function doesn't * actually* submit (fire the event), it attaches a submit handler for when the submit happens (which the normal behavior is doing)...since you're calling it in a submit situation, just remove the handler wrapper and actually submit, like this:

jQuery.fn.submitWithAjax = function() {
  $.post(this.attr("action"), this.serialize(), null, "script");
  $('.spinning').show(); 
  $("#dialog_form").dialog("close")
  return false;
};

Note the .attr("action") change, because this is not a jQuery object, not a <form> DOM element since it's directly in the plugin.


Previously, you were attaching an additional submit handler each time, which is why you get 1, 2, 3.... submits, by just calling the submit code you want, this won't happen, since inside submitHandler is the valid place to go ahead and submit anyway.

As an aside, the callback function to $.post() is optional, so you can leave off that null, and it'll function properly.

0

精彩评论

暂无评论...
验证码 换一张
取 消