Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
dispatch change event on select tag that has dynamic selection

I want to dispatch the event so I can run the function inside the eventlistener

I've tried:

var event = new Event('change'); 
i.dispatchEvent(event);

but it didn't work without giving any error

let i = document.querySelector('#i');

i.querySelector('[value="7"]').selected = true;

//dispatch event
let ev = new Event("change");
i.dispatchEvent(ev); 

i.addEventListener('change', e=>{
  alert('selected : '+e.target.value);
});
<select id="i">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
</select>

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You are dispatching the event before you add event listener, that's why it's not working. You need to add event listener first, then dispatch the event:

let i = document.querySelector('#i');

i.querySelector('[value="7"]').selected = true;

// Add event listener first
i.addEventListener('change', e=>{
  alert('selected : ' + e.target.value);
});


// Dispatch event after event listener is added
let ev = new Event("change");
i.dispatchEvent(ev); 
<select id="i">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
</select>

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda