I'm having a lot of trouble doing what I need.
I'll explain the code and the problem:
The user must choose the ice cream tastes that he wishes by clicking on the checkboxes of the image and then send the order through the "Send Order" button.
<!-- Modal -->
<div id="vasoModal" class="modal">
<div class="modal-content">
<h4 class="modal-title">Vasito</h4>
<h6>Seleccione hasta dos gustos</h6>
<form 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>
My JavaScript code validates which tastes were clicked and saves them in an array. Then I should do a POST of that fix to the Java controller.
/* 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').attr('action', clickeados + '/pedido');
}
});
The post is done but the Spring driver receives the array as "[object HTMLInputElement]" and not as an array so I can validate it ....
Here I am stuck, I do not know how to validate from the controller the data of the arrangement (the checkboxes that were clicked) to then be able to show the tastes selected to the user in a new page.
Any ideas?
This is the driver code, but I do not think it's okay because it does not work for me:
@RequestMapping(value="{gustos}/pedido", method = RequestMethod.POST)
public void pedido(HttpServletRequest request) {
Map<String, String[]> dataFeed = request.getParameterMap();
for (Map.Entry<String, String[]> entry : dataFeed.entrySet()) {
for (String str : request.getParameterValues(entry.getKey())) {
int gustoId = Integer.parseInt(entry.getKey());
Gusto gusto = gustoService.findGustoById(gustoId);
System.out.println(gusto.toString());
// if (str.equals("some-value")) { // where some-value is value="some-value" on your checkbox
// // do something with the gusto
//
}
}
}