Home > Mobile >  How to check whether buttons are pressed in the correct order?
How to check whether buttons are pressed in the correct order?

Time:10-06

In my project, I want to check whether the buttons are pressed in the correct sequence or not. The correct sequence is stored in an array. For that, I added an event listener using a for loop and created a separate function for the event listener. But the function is not getting executed while running the loop, only giving an alert without clicking on the button. Here is the code :

    var points = [1,2,3,4,5];
    
    for(var j=0;j<points.length;j  )
    {
      checkButton(j);
    }
    
    
    function checkButton(j)
    {
      $("button").on("click", function(){
        if($(this).text()== points[j] )
        {
          alert("compleated step " (j 1));
        }
        else
        {
          alert("incorrect step " (j 1));
        }
      });
    }

Thanks for your time !!

CodePudding user response:

Due to your for-loop you are registering the same event-handler multiple times. All you need to do is to register the click-handler once and adjust the logic of checking wheter the buttons are pressed in the correct order.

You should consider using the value attribute to assign each button a value as this allows you to uncouple the value from the text.

HTML

<div>
  <p>Click buttons in correct sequence!</p>
  <button value="1">#1</button>
  <button value="2">#2</button>
  <button value="3">#3</button>
  <button value="4">#4</button>
  <button value="5">#5</button>
</div>

JS

var order = [2,4,1,3,5]
var nextOrderIndex = 0;
// register handler once
$("button").on("click", function() {
  // parse text of button to int for correct comparison
  var buttonValue = parseInt($(this).attr("value"))
  if (buttonValue == order[nextOrderIndex]) {
    // count up for next check
    // use modulo to start back at 0 when counter reaches order.length
    nextOrderIndex = (nextOrderIndex   1) % order.length;
    alert("Correct");
  } else {
    alert("Incorrect");
  }
});

See working Fiddle

Edit: adjusted for random order

  • Related