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

179
Vistas
How do I select the next item in an array when a user clicks on a button?

I am making quiz using 4 buttons to answer the questions (I have 6 questions in total).

How do I get the next set of questions from my array? It looks like this:

var questions = [{
       question: "the question!".
       answer1: "choice1",
       answer2: "choice2",
       answer3: "choice3",
       answer4: "choice4",
       correct: "choice3",

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

0

Just track the current index in the array, and when they click, increment the index. And then I'd just have a render method which takes the index as a parameter. Something like:

const questions = [{
       question: "the question!",
       answer1: "choice1",
       answer2: "choice2",
       answer3: "choice3",
       answer4: "choice4",
       correct: "choice3"

}, {
       question: "the next question!",
       answer1: "A",
       answer2: "B",
       answer3: "C",
       answer4: "D",
       correct: "C"
}];

var currentQuestionIndex = 0;

const c = document.getElementById('content');

const render = (idx) => {
    const q = questions[idx];
    c.innerHTML = `<strong>${q.question}</strong>
        <p><label><input name="q" type="radio"/>${q.answer1}</label>
        <p><label><input name="q" type="radio"/>${q.answer2}</label>
        <p><label><input name="q" type="radio"/>${q.answer3}</label>
        <p><label><input name="q" type="radio"/>${q.answer4}</label>
    `;
}

render(currentQuestionIndex);

document.getElementById('btn').addEventListener('click', () => {
    currentQuestionIndex = (currentQuestionIndex + 1) % questions.length;
    render(currentQuestionIndex);
});
<div id="content"></div>

<button id="btn">Next</button>

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