1

i'm trying force an event from javascript.

I have a "select" element in the html and i'm forcing the value of this from javascript but this does not trigger the "change" event. How can I force the event?

HTML:

<th><select id="filtro_select_periodo"></select></th>

Javascript:

window.onload = function() { 
    let fecha = new Date();

    cargarSelectPeriodo();

    filtro_select_periodo.value = fecha.getMonth();
};

filtro_select_periodo.addEventListener("change", (e) => {
    let fecha = new Date();

    fecha = new Date(fecha.getFullYear(), e.value, fecha.getDate())

    let periodo = getFechaDesdeHasta(fecha);

    filtro_periodo_desde.value = periodo.desde;
    filtro_periodo_hasta.value = periodo.hasta;

    actulizarListado();
});
Nof
  • 13
  • 3

2 Answers2

0

Events don't apply to changes caused by JavaScript, only for user actions. Otherwise every JS check, formatter, etc. would cause an infinite loop when changing the user input and thus triggering itself again.

You should move the code from filtro_select_periodo.addEventListener("change", (e) => { [code] } to a function and call it after changing the value.

Sebastian
  • 2,472
  • 1
  • 18
  • 31
0

You can trigger JQuery events with JQuery's .trigger('eventname') method. Like

$(filtro_select_periodo).change(function (e) => { }); // add event listener
$(filtro_select_periodo).change(); // trigger the event in your window.onload function

See: https://api.jquery.com/change/

mhpcc
  • 120
  • 1
  • 12