I'm trying to do a simple submit () through JavaScript but in the console I get an error of "too much recursion" and there the program is slowed down.
I'm trying to validate the clicks within a modal and save the input's clicked into an array, if then the fix meets certain conditions, the submit is done, otherwise an error message will appear for 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 () is fine if nothing is clicked and it shows the error message without redirecting, but when having input's clicked and doing the submit () the console message "too much recursion"!
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 can it be solved?