I have two select
that work with the event onchange
but I want that if I select the same value of the second select
again, it will execute its callback function again... Example: if in the select query I select the value "forecast" it shows the console.log
with the text of the year and the number of the selection, but changing the year and selecting the value again would not show anything because nothing changes in the second select... what event can I use for this, or what could I do... Thanks in advance
window.addEventListener('load', function () {
//Declaramos la variable global
let annoSeleccionado = "";
//valor del anno en en select
const selectAnno = document.getElementById("annos");
selectAnno.addEventListener('change', function () {
annoSeleccionado = parseInt(this.options[selectAnno.selectedIndex].value);
console.log(annoSeleccionado);
});
//selecciono el select de valores
var valorseleccionado = document.getElementById('select');
//tomo el valor del select cuando cambie y muesto los datos de interes
valorseleccionado.addEventListener('change', function () {
const opcion = this.options[select.selectedIndex].value;
//de nuevo podemos acceder a la variable sin problemas
console.log('Se ha seleccionado la combinación', annoSeleccionado,'y', opcion);
});
});
<div>
<div class='elementos'>
<label for="SelAnno">Anno</label>
<select name='SelAnno' id='annos'>
<option value="-1">Selecciona Año</option>
<option value="2019">2019</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
</select>
</div>
</div>
<div>
<div class='elementos'>
<label for='pruebas'>Consulta</label>
<select name="pruebas" id="select">
<option>Selecciona</option>
<option value="1">Prevision</option>
<option value="2">Otros datos</option>
</select>
</div>
<div class='menulateral ' id='lateral'>
</div>
</div>
Try using click instead of change.
For more functions on EventListener look at the following link:
https://www.w3schools.com/js/js_htmldom_eventlistener.asp
You can use the concept of "state-effect", making both events share the same effect that modifies the state and does the operations you need. For example if you select the sequence 2019 ---> Other data; and you can see the message "Combination 2019 and 2 has been selected"; when selecting 2018, you will see the new message "The combination 2018 and 2 has been selected", without having to choose the second select option again, because it is remembered in the "state". In your case if you want to execute an asynchronous function you can execute it in the "effect". In the example below I use setTimeout to simulate the Ajax calls and execute different effects depending on the chosen year.