0

I have a regular form, when the submit button is clicked I want to hide the submit button, and if any form values change after submitting it'll auto submit again.

I'm using the following code and it works, but each time I update the form data and the form is automatically submit, in the JS console I can see it's being submit many many times, and the number increases each time it auto submits. e.g. first auto submit posted once, second auto submit posted 4 times, third auto submit posted 8 times and then the form starts getting really slow due to this.

jQuery(function($) {

$(document).on("click",'#bookingbutton', function() {
    $( "#bookingbutton" ).css( "display", "none" );
    $( ".bookroom1" ).addClass( "bookroom1-submit" );

    $(".bookroom1-submit").change(function() {
        $("#bookingbutton").click();
    });

});

});
0

2 Answers 2

2

That is because each time you call $("#bookingbutton").click() you are registering again a change listener in .bookroom1-submit.

Try replacing

$(".bookroom1-submit").change(function() {
    $("#bookingbutton").click();
});

With

$(".bookroom1-submit").off('change').on('change', function() {
    $("#bookingbutton").click();
});

That should do it.

EDIT

Some further explanation on the problem:

  1. Submit button is clicked.
  2. It adds a class to the button and registers a change listener.
  3. Next time, when an input changes, you are triggering a click on the button, which will cause 1. and 2. to happen again. Now you will have 2 listeners for change.
  4. it will continue to grow exponentially.

Another alternative is, instead of $("#bookingbutton").click(); use $("#your-form-id").trigger('submit');

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the great explaination!
1

Use jquery off and then one:

jQuery(function ($) {
      $(document).off("click", '#bookingbutton').one
      ("click", '#bookingbutton', function () {
          $("#bookingbutton").css("display", "none");
          $(".bookroom1").addClass("bookroom1-submit");

          $(".bookroom1-submit").change(function () {
              $("#bookingbutton").click();
          });

      });

  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.