2

On the Yahoo weather website, there is a select element which could be retrieved by:

let sel = document.querySelector('select');

You can manually select different options (Temperature, Wind, and Precipitation) and see the next 24-hour forecast for each one. The problem is that when you change the option programmatically (as below), although the selected option changes, the onChange event not triggers (i.e., forecasts not update):

sel.selectedIndex = 1;

sel.selectedIndex = 2;

I've tested different solutions prepared on similar threads (like this one and this one), but unfortunately non of them works. Any helps would be appreciated in advance.

2
  • change() event is not triggered automatically, you need to trigger it, as sel.change(); after setting the selectedIndex Commented Apr 4, 2021 at 6:33
  • Either calling sel.change() or sel.onchange() returns this error: Uncaught TypeError: sel.onchange is not a function. Commented Apr 4, 2021 at 6:36

1 Answer 1

4

You need to use below code:-

const sel = document.querySelector('select');
sel.value = 'precipitation'; // You can change this value to whatever you want
sel.dispatchEvent(new Event('change', {'view': window,'bubbles': true}));

Sign up to request clarification or add additional context in comments.

2 Comments

That sounds greate! Thank you @Diwakar Singh. That worked for me. Would you please explain the last line a bit more?
I was trying this for the last 15 mins, I was just missing the bubbles: true setting, my bad. And I guess view: window is not required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.