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>
CodePudding user response:
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>