0

I have a select drop-down has 4 option items.

  • I want to make an auto on change to all of my select items one after one after every 2 second.
  • I try to loop for 4 times and make an auto on-change according to the number of the option item but doesn't work.
  • So how can I do these 4 on-change automatically?
<!DOCTYPE HTML>
<html>
   <head>
     <meta charset="UTF-8">
   </head>
   <body>
     <select class="cars">
     <option value="volvo">Volvo</option>
     <option value="saab">Saab</option>
     <option value="mercedes">Mercedes</option>
     <option value="audi">Audi</option>
     </select>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
     <script>
     $ (document).ready (function() {
     var i;
     for (i = 0; i < 4; i++) {
     setTimeout (function() {
     $ (".cars").prop ('selectedIndex', i); // make on change according to its number item
     }, 2000);
     }
     });
     </script>
   </body>
</html>

4b0
  • 21,981
  • 30
  • 95
  • 142
  • Related: [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Taplar Jun 06 '19 at 22:28

2 Answers2

0

maybe this will help

function autoAjax(i) {
    $(".cars").prop("selectedIndex",i);


    setTimeout(function() {autoAjax((i+1)%4);},2000);

}

autoAjax(0);

i put the contents you had on the set timeout function into a different named function that takes the index of the select option as a parameter.

at the end, it will create a timeout and call the same function after two seconds, with an incremented value of i modulus 4 so that it can loop around.

pauldrodriguez
  • 480
  • 2
  • 6
0

You can use setTimeout loop with recursion and trigger like below.

let i = 0;
function fntimeout() {
  setTimeout(function() {
    if (i == 4) // Reset Counter if you want infinite change
      i = 0;
    $(".cars").trigger('change');
    $(".cars").prop('selectedIndex', i);
    fntimeout();
    i++;
  }, 2000);
}
fntimeout();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
4b0
  • 21,981
  • 30
  • 95
  • 142