jqueryform-submitdouble-submit-prevention

Prevent submit form twice with change event


i hava a form with a hidden submit button and one text input. In the text input, with jQuery i attached to it a change event that submits the form. The thing is that if i hit enter on the input, then the form submits twice. I think is because the enter submits the form and the input detects a change event and it submit the form again. I have two questions: - Is my thought right? - How can i fix this?

This is the javascript:

$("input.price").live('change', function () {
  $(this).closest('form').submit();
});

Edit: I think that the e.preventDefault() is preventing the default of the event "change" but no preventing the event "submit".. i try this before the event "change" with no luck but maybe im close to the solution:

$("input.price").live('submit', function (e) {
       e.preventDefault();
});

Solution

  • Finally i came out with a solution! The thing was that.. as Mike C. says, the extra code could help to solve the problem. The problem was that the form that i'm trying to submit it's an Ajax.BeginForm of MVC so.. the main problem is the ajax submit of that form, that was the second submit!

    I couldn't change that behavior.. only changing the Ajax.Beginform with a Html.Beginform.. thing that i don't want to do. So.. i came out with this "rusty" solution:

    $("input.price").live('keypress', function (e) {
         if (e.keyCode == 13) {
            $(this).attr('data-submitting', true);
         }
    });
    
    $("input.price").live('change', function (e) {
         if (!$(this).attr('data-submitting')) {
             $(this).closest('form').submit();
         }
    });