Search code examples
javascripttampermonkey

TextBox update in order from an array?


How would I be able to make it so the TextBox updates in order based on the Array?

I have 5 and 10 in the 'prices' array, I want it to go to 5 and then 10 and so fourth, what's the most efficient way of doing this? Right now it picks a random number in the array.

const pricetext = document.getElementById('ctl00_cphPrice')
var prices = ["5", "10"]

function update() {
pricetext.value = prices[Math.floor(Math.random() * prices.length)];
}

update()

Solution

  • You could take a closure over the index and increment it after assigning and adjust to the length of the array.

    const
        pricetext = document.getElementById('ctl00_cphPrice'),
        prices = ["5", "10"],
        update = (index => () => {
            pricetext.value = prices[index++];
            index %= prices.length;
        })(0);
    
    setInterval(update, 2000);
    <input type="text" id="ctl00_cphPrice" />