For some reason, I can set the select option in a dropdown list using javascript without a problem but when I execute the same code using an event listener the option does not change.
html:
<select id="sel">
<option value="car">1</option>
<option value="bike">2</option>
<option value="cycle">3</option>
</select>
<button id = "button" type = "button" class = "">Test</button>
Javascript:
const button = document.getElementById('button')
button.addEventListener('click', e=>{
console.log('executed')
document.getElementById('sel').value = 'bike'
})
Does not change the value eventhough executed is posted to the console. However, the following works and changes the option to 2
document.getElementById('sel').value = 'bike'
So how come document.getElementById('sel').value = 'bike' works when executed outside of the event listener but does not work inside of the event listener?
button
defined? – Xeothid = "button",
should beid='button'
, without the comma. – StackSlavebutton
properly – dippas