There is such a code, it works, but the possibility of an infinite loop confuses

orderForm.on('submit', function(event) { event.preventDefault(); //some code here this.submit(); }) 

Why does not an infinite loop occur, is everything correct in this code?

What does an example of correct code look like in such situations?

    1 answer 1

    The HTMLFormElement.submit method does not generate a submit event based on the fact that the programmer deliberately directly sends the form. Therefore, this design does not loop

    You can use the standard form submission blocking and send it manually using the submit method, for example, if you have your own validations for the fields:

     $("#orderForm").on("submit", function(event) { event.preventDefault(); var $orderError = $("#orderError"); $orderError.text(""); var _this = this; validate($("#orderValue").val(), function(isValid) { if (isValid) { _this.submit(); } else { $orderError.text("Incorrect order value"); } }); }); function validate(value, onResult) { //асинхронная валидация setTimeout(function() { onResult(value.length >= 3); }, 1000); } 
     .error { color: red; } 
     <form id="orderForm" action="test"> <input id="orderValue" /> <input type="submit" value="Send" /> <div id="orderError" class="error"></div> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    • +1, but: the example looks far-fetched), because instead of this.submit(); you could call event.preventDefault(); by condition. I use form.submit(); when the asynchrony is present in the $().submit handler, and the handler is required to work before the result of checking the condition of the form submission is known. - Igor
    • @Igor agree, the synchronous version looks unconvincing. I tried to remake the asynchronous version so as not to over-complicate the example. We have almost no <form> tags at work, so I myself got used to submit the “form” data by an Ajax request to send - Regent