I have a <select>
with several <option>
that take different values as the user chooses a different one. The problem is that the first option will never take its value unless the user triggers the 'change' event, that is, first chooses another option from the list and then chooses the first option again.
JQuery:
$('#categorias').on('change', () => {
var value = $('#categorias').val();
if(value === "Dulces de Leche") {
$('#idCategoria').val(1);
}
else if(value === "Cremas") {
$('#idCategoria').val(2);
}
else if(value === "Chocolates") {
$('#idCategoria').val(3);
}
if(value === "Frutales") {
$('#idCategoria').val(4);
}
});
HTML:
<div class="col s12 l8">
<!-- TODO: Hacer una clase aparte para hacer esto dinámico -->
<input id="idCategoria" th:value="0" th:field="*{idCategoria}" hidden="hidden"/>
<select id="categorias" th:field="*{categoria}">
<option value="" disabled="disabled">Categoria</option>
<option value="Dulces de Leche">Dulce de Leche</option>
<option value="Cremas">Cremas</option>
<option value="Chocolates">Chocolates</option>
<option value="Frutales">Frutales</option>
</select>
</div>
What event can I use here to have the same functionality but that the first option also takes its value in case the user submits directly, without first having chosen another option?
There is no event that will serve you for this, you could carry out when loading the page the setting of the value of idCategory to 1 directly or control to enable the submit button (submit) when the options have been chosen, forcing the user to choose yes or yes a. Example how it would be done:
You could have the value set on the submit form, something like this:
Another possibility would be that the "idCategory" element already has the value 0 by default.
Luck!