Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
How to check whether buttons are pressed in the correct order?

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 !!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda