Estoy aprendiendo javascript y escribiendo un programa Quiz como parte del proceso de aprendizaje.

<!DOCTYPE html> 
<html>          
        <head>  
                <meta charset="UTF-8">                                              
        </head> 
        <body>  
                <form type="submit" onsubmit = "populateQuestion()">                
                        <h2 id="question">Question goes here</h2>                   
                        <input name = "option" type="radio" value="A"><span id = "choiceA">First option here</span><br/>
                        <input name = "option" type="radio" value="B"><span id = "choiceB">Second option here</span><br/>
                        <input name = "option" type="radio" value="C"><span id = "choiceC">Third option here</span><br/>
                        <input name = "option" type="radio" value="D"><span id = "choiceD">Fourth option here</span><br/>
                        <button type = "submit">Submit</button>                     
                </form>                       
        </body>                                                                     

<script>
var question = document.getElementById("question");
var choiceA = document.getElementById("choiceA");
var choiceB = document.getElementById("choiceB");
var choiceC = document.getElementById("choiceC");
var choiceD = document.getElementById("choiceD");

var quesIndex = 0;
var defQuestions = [
        {
                question : "Q01?",
                choiceA : "A1",
                choiceB : "B1",
                choiceC : "C1",
                choiceD : "D1",
                answer : "A"
        },
        {
                question : "Q02?",
                choiceA : "A2",
                choiceB : "B2",
                choiceC : "C2",
                choiceD : "D2",
                answer : "A"

        },
        {
                question : "Q03?",
                choiceA : "A3",
                choiceB : "B3",
                choiceC : "C3",
                choiceD : "D3",
                answer : "B"

        },
        {
                question : "Q04?",
                choiceA : "A4",
                choiceB : "B4",
                choiceC : "C4",
                choiceD : "D4",
                answer : "B"

        }
];

function renderQuestion() {
        question.innerHTML = defQuestions[quesIndex].question;
        choiceA.innerHTML = defQuestions[quesIndex].choiceA;
        choiceB.innerHTML = defQuestions[quesIndex].choiceB;
        choiceC.innerHTML = defQuestions[quesIndex].choiceC;
        choiceD.innerHTML = defQuestions[quesIndex].choiceD;
}

function populateQuestion() {
        console.log(quesIndex);
        renderQuestion();
        quesIndex += 1;
}

populateQuestion();
</script>
</html> 

Cuando cargué la página, populateQuestion() ejecutó y cargó la pregunta y las opciones predeterminadas (el primer elemento de la matriz defQuestions). Esta parte está funcionando bien.

Image

Cuando hago clic en el botón Submit, se supone que la siguiente pregunta está cargada. Pero la siguiente pregunta no se está cargando.

console.log(quesIndex); imprime solo 0 y luego se borra la ventana de la consola.

¿Hay algo malo en la implementación?

0
Nayab Basha Sayed 27 oct. 2019 a las 18:39

3 respuestas

La mejor respuesta

No estoy seguro de cómo piensa procesar el envío del formulario, pero su implementación actual enviará el formulario, lo que hará que la página se vuelva a cargar y que se reinicie el script.

Debe agregar un detector de eventos para capturar el evento de envío del formulario y procesarlo usted mismo (espero que almacene las respuestas dadas por los usuarios en una matriz)

var question = document.getElementById("question");
var choiceA = document.getElementById("choiceA");
var choiceB = document.getElementById("choiceB");
var choiceC = document.getElementById("choiceC");
var choiceD = document.getElementById("choiceD");

var quesIndex = 0;
var defQuestions = [{
    question: "Q01?",
    choiceA: "A1",
    choiceB: "B1",
    choiceC: "C1",
    choiceD: "D1",
    answer: "A"
  },
  {
    question: "Q02?",
    choiceA: "A2",
    choiceB: "B2",
    choiceC: "C2",
    choiceD: "D2",
    answer: "A"

  },
  {
    question: "Q03?",
    choiceA: "A3",
    choiceB: "B3",
    choiceC: "C3",
    choiceD: "D3",
    answer: "B"

  },
  {
    question: "Q04?",
    choiceA: "A4",
    choiceB: "B4",
    choiceC: "C4",
    choiceD: "D4",
    answer: "B"

  }
];


var questionnaire = document.getElementById("questionnaire");

function renderQuestion() {
  question.innerHTML = defQuestions[quesIndex].question;
  choiceA.innerHTML = defQuestions[quesIndex].choiceA;
  choiceB.innerHTML = defQuestions[quesIndex].choiceB;
  choiceC.innerHTML = defQuestions[quesIndex].choiceC;
  choiceD.innerHTML = defQuestions[quesIndex].choiceD;
}

function populateQuestion() {
  console.log(quesIndex);
  renderQuestion();
  quesIndex += 1;
}

function onsubmit(e) {
  e.preventDefault(); //prevent form from actually posting
  var a = questionnaire.querySelector('input[name = option]:checked'); 
  
  console.clear();
  console.log("Q:",quesIndex,"Answer:",a.value);
  a.checked=false;//deselect it ready for new question
  populateQuestion();
}

questionnaire.addEventListener('submit', onsubmit, false);


populateQuestion();
form {
    margin-bottom:100px;/* just some space for the console log in the snippet*/
}
<form id="questionnaire" type="submit">
  <h2 id="question">Question goes here</h2>
  <input name="option" type="radio" value="A"><span id="choiceA">First option here</span><br/>
  <input name="option" type="radio" value="B"><span id="choiceB">Second option here</span><br/>
  <input name="option" type="radio" value="C"><span id="choiceC">Third option here</span><br/>
  <input name="option" type="radio" value="D" required><span id="choiceD">Fourth option here</span><br/>
  <button type="submit">Submit</button>
</form>
2
Moob 27 oct. 2019 a las 16:15

Aquí está el código revisado, funciona en jsfiddle.net. Entonces, básicamente necesitará actualizar quesIndex antes de presentar una nueva pregunta.

    <!DOCTYPE html> 
<html>          
        <head>  
                <meta charset="UTF-8">                                              
        </head> 
        <body>  
                <form type="submit" onsubmit = "populateQuestion()">                
                        <h2 id="question">Question goes here</h2>                   
                        <input name = "option" type="radio" value="A"><span id = "choiceA">First option here</span><br/>
                        <input name = "option" type="radio" value="B"><span id = "choiceB">Second option here</span><br/>
                        <input name = "option" type="radio" value="C"><span id = "choiceC">Third option here</span><br/>
                        <input name = "option" type="radio" value="D"><span id = "choiceD">Fourth option here</span><br/>
                        <button type = "submit">Submit</button>                     
                </form>                       
        </body>                                                                     

<script>
var question = document.getElementById("question");
var choiceA = document.getElementById("choiceA");
var choiceB = document.getElementById("choiceB");
var choiceC = document.getElementById("choiceC");
var choiceD = document.getElementById("choiceD");

var quesIndex = 0;
var defQuestions = [
        {
                question : "Q01?",
                choiceA : "A1",
                choiceB : "B1",
                choiceC : "C1",
                choiceD : "D1",
                answer : "A"
        },
        {
                question : "Q02?",
                choiceA : "A2",
                choiceB : "B2",
                choiceC : "C2",
                choiceD : "D2",
                answer : "A"

        },
        {
                question : "Q03?",
                choiceA : "A3",
                choiceB : "B3",
                choiceC : "C3",
                choiceD : "D3",
                answer : "B"

        },
        {
                question : "Q04?",
                choiceA : "A4",
                choiceB : "B4",
                choiceC : "C4",
                choiceD : "D4",
                answer : "B"

        }
];

function renderQuestion() {
        question.innerHTML = defQuestions[quesIndex].question;
        choiceA.innerHTML = defQuestions[quesIndex].choiceA;
        choiceB.innerHTML = defQuestions[quesIndex].choiceB;
        choiceC.innerHTML = defQuestions[quesIndex].choiceC;
        choiceD.innerHTML = defQuestions[quesIndex].choiceD;
}

function populateQuestion() {
        console.log(quesIndex);
        quesIndex += 1;
        renderQuestion();
}

populateQuestion();
</script>
</html> 
-1
Protocleus EDM 28 oct. 2019 a las 03:16

Intente adjuntar una identificación a su formulario y un detector de eventos de envío en el formulario y evite el comportamiento predeterminado del formulario para evitar que su formulario vuelva a cargar la página y haga su lógica allí.

1
Ali 27 oct. 2019 a las 16:06