0

I am running a JavaScript file on page load, however since the page reloads after clicking the search button the variable is redefined and the loop starts from the beginning again. Here is my code.

var acctNum = ["8AXXXXX0",
               "8XXXXXX1",
               "8XXXXXX2"]

    var i = 1;

    function myLoop () {  
        setTimeout(function () { 
            console.log(i);
            document.getElementsByName("customerAccountNumber")[0].value=acctNum[i - 1];  //enter account number
            $("[name='listUsers.x']").click(); //search 
            i++;                 
            if (i < acctNum.length) {   
                myLoop();     
            }       
        }, 3000)
    }

    myLoop();

The code works for the first iteration but like I said since the page reloads i is redefined and it simply just loops through the very first account number. Any help would be appreciated.

Thank you,

  • You'll need to store the variable somewhere that can persist between page calls. There are several possible solutions (cookies, local storage, server-side database, etc.). Which you use depends on what kind of security and architecture you want. – Scott Marcus Dec 26 '19 at 17:54
  • FYI: [`document.getElementsByName("customerAccountNumber")[0]` is super inefficient](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). Use `document.querySelector("[name='customerAccountNumber']")` instead. – Scott Marcus Dec 26 '19 at 17:55
  • If I define local storage in the code wont I run into the same issues where it will re-define on page load since the script re-runs every load? I am not terribly familiar with local storage so pardon my unfamiliarity. I also have never worked with cookies before so I may have to do some research. – Tren Dinius Dec 26 '19 at 18:05
  • With any of these methods, you store key/value pairs that will persist between page calls and then you modify your page code to first check to see if a key exists in storage. If so, retrieve it and use it, if not start with a default value. So, in your case, you would first check to see if a counter was stored, if so get it and use that as the starting loop counter. If not, start from a default. In either case, just before the script ends, write the current counter value into local storage for next time. – Scott Marcus Dec 26 '19 at 18:13

0 Answers0