Skip to content
Advertisement

change select values one after another with tampermonkey

I have select boxes as part of a larger form. I have to pick an option in one box before options in the next populate. I get as far as selecting the first box and triggering the second to populate but can’t get the second one to select.

my code:

var option1Box = document.getElementById('1stBox');
var option2Box = document.getElementById('2ndbox');
option1Box.selectedIndex = 32;
option1Box.dispatchEvent (evt); //this populates the second box
option2Box.selectedIndex = 47;

I do know that JavaScript just runs everything, not one thing at a time, so I know (or pretty sure) my struggles are with forcing the code to wait for the previous line to run. I need to make sure option1Box.dispatchEvent (evt); runs before option2Box.selectedIndex = 47;.

Advertisement

Answer

The problem you have is whatever is adding the options is taking time time so you need to add a pause. Nothing really built in to wait so you need to code something that will do that.

You can add code to wait for the element’s options to be loaded. You can do it a few ways, but easiest way is to keep looking at the number of options.

document.getElementById('1stBox').addEventListener("change", function() {
  document.getElementById('2ndbox').innerHTML = `
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
  `;
});


const waitForSelectIndex = (sel, index) => {
  return new Promise(resolve => {
    function check() {
      if (sel.options.length >= index) {
        resolve();
      } else {
        window.setTimeout(check, 10);
      }
    }
    check();
  });
}

const runIt = async() => {
  const option1Box = document.getElementById('1stBox');
  const option2Box = document.getElementById('2ndbox');

  await waitForSelectIndex(option1Box, 5);
  option1Box.selectedIndex = 5;
  option1Box.dispatchEvent(new Event("change")); 

  await waitForSelectIndex(option2Box, 2);
  option2Box.selectedIndex = 2;
  option2Box.dispatchEvent(new Event("change")); 
}

runIt();
<select id="1stBox">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
  <option>7</option>
</select>

<select id="2ndbox"></select>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement