0
votes

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?

1
How is button defined?Xeoth
Instead of showing individual pieces, can you make a runnable code snippet to demonstrate?David
id = "button", should be id='button', without the comma.StackSlave
it is working as expected, if you set the button properlydippas
<button id = "button", type = "button" class = ""> Test </button> why do you have spaces and comma ?Met Br

1 Answers

0
votes

All, thanks to everyone who commented, you are correct it, the code does work fine in vanilla javascript. I am using materialcss as my styling theme and for whatever reason, when materialcss is applied, the event listener does not work. This is not the case when materialcss is no longer applied. I will post about this soon.