Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Force JavaScript to wait for a click (loops)

I have 4 buttons different colors and I want to check my clicks against the given array.

What I’m expecting:is giving me the result of my click each time and with "i" increasing each time.

instead:Im getting 15*times the answer. with "i" printing 15 times as "15", instead of 1>2>3>4>5>6….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var arrColor = ['blue', 'yellow', 'green', 'red', 'blue', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'green', 'green', 'blue', 'yellow'];

var i = 0;
for (var i = 0; i < 15; i++) {
    $(".btn").click(function (event) {
        console.log(i); // check on i
        if (arrColor[i] === event.target.id) {
            console.log("great");
        }
        else {
            console.log("Wrong");
        }
    });

}

enter image description here

>Solution :

Your code is adding 15 event handlers for the buttons. Try using one event handler, incrementing i and using an if statement to make sure i is under 15.

var arrColor = ['blue', 'yellow', 'green', 'red', 'blue', 'blue', 'yellow', 'blue', 'blue', 'yellow', 'yellow', 'green', 'green', 'blue', 'yellow'];

let i = 0;

$(document).on("click", ".btn", function() {
  if (i <= 15) {
    if ($(this).attr("id") == arrColor[i]) {
      console.log("great");
    } else {
      console.log("wrong");
    }
    i++;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn" id="blue">B</button>
<button class="btn" id="green">G</button>
<button class="btn" id="yellow">Y</button>
<button class="btn" id="red">R</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading