I'm trying to do a simple submit() through JavaScript but in the console I get a "too much recursion" error and the program stops there.
I am trying to validate the clicks within a modal and save the clicked input's in an array, if the array then meets certain conditions the submit is done, otherwise an error message is output to the user.
/* Validar checkboxes clickeados */
var checkboxes = document.querySelectorAll('.single-checkbox');
var clickeados = [];
checkboxes.forEach(elem => {
elem.addEventListener('change', (event) => {
event.stopPropagation();
if(elem.checked) {
if(!clickeados.includes(elem)){
clickeados.push(elem);
console.log(clickeados);
}
}
else{
if(clickeados.includes(elem)){
clickeados.pop(elem);
console.log(clickeados);
}
}
});
});
/* Validar cuantos gustos fueron seleccionados antes de hacer el submit */
$('#vasitoForm').on('submit', (event) =>
if(clickeados.length == 0){
event.preventDefault();
document.getElementById("errorGustos").innerHTML = "Debe seleccionar por lo menos un gusto";
}
else if(clickeados.length > 0 && clickeados.length < 3){
$('#vasitoForm').submit();
}
});
The preventDefault() works fine if nothing is clicked and it shows the error message without redirecting, but when I have input's clicked and do the submit() I get the "too much recursion" message on the console!
The HTML is as follows:
<!-- Modal -->
<div id="vasoModal" class="modal">
<div class="modal-content">
<h4 class="modal-title">Vasito</h4>
<h6>Seleccione hasta dos gustos</h6>
<form th:action="@{/pedido}" id="vasitoForm" method="post">
<table class="tabla">
<tr th:each="gusto : ${gustos}">
<td class="flavour" th:text="${gusto.nombre}"></td>
<td><input class="single-checkbox" type="checkbox" th:value="${gusto.id}"/></td>
</tr>
</table>
<p id="errorGustos"></p>
<button type="submit" class="btn-submit">Enviar Pedido</button>
</form>
</div>
</div>
Any idea why this happens and how it can be fixed?
I analyze the code for you to see the problem:
This code is equivalent to yours, but we give a name to the function to execute:
So:
submit
the execution ofcallbackFunction
.submit
callbackFunction
It is called tocallbackFunction
cancels the current event withevent.preventDefault();
.callbackFunction
checks that everything is fine and the submit can be done, so it callsform.submit()
, which fires the eventsubmit
. GO TO 3You enter a loop in which the submit event is stopped and a new event is fired. It's an indirect recursion loop with no base case, so it never ends and the JS interpreter runs out of memory, causing the crash.
The solution is the next: