title: Previous question button in JavaScript and saving users answers
body: <p>I'm trying to make a JavaScript quiz and I need the user to be able to go to the previous question to see or change his/her answer . The next button works with me but I have a problem with the previous button . what I also need is when the user goes back, the original answer should be saved. here is my code. I also put it on <a href="https://codepen.io/f6m7/pen/gOLQBbm" rel="nofollow noreferrer">codepen</a></p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const questionNumber = document.querySelector(".question_number");
  const questionText = document.querySelector(".question_text");
  const optionContainer = document.querySelector(".option_container");
  const answerIndecatorContainer = document.querySelector(".answer_indicator");
  const homeBox = document.querySelector(".home_box");
  const quizBox = document.querySelector(".quiz_box");
  const resultBox = document.querySelector(".result_box");
  const registerBox = document.querySelector(".register_box");
  const timeBox = document.querySelector("time_box");
  
  let questionCounter = 0;
  let currentQuestion;
  let availableQuestions = [];
  let availableOptions = [];
  let correctAnswers = 0;
  let attempt = 0;
  
  //push the question into availableQuestions array
  function setAvailableQuestions(){
      const totalQuestion = quiz.length;
      for (let i=0; i&lt;totalQuestion; i++){
          availableQuestions.push(quiz[i])
      }
  }
  
  // set question number and question options
  function getNewQuestions(){
      //set question number
      questionNumber.innerHTML = "Question " + (questionCounter +1) + " of " + quiz.length;
      // set question text
      //get random questions
      const questionIndex = availableQuestions[Math.floor(Math.random() * availableQuestions.length)]
      currentQuestion = questionIndex;
      questionText.innerHTML = currentQuestion.q;
      //get the position of 'questionIndex' from the availableQuestions array
      const index1 = availableQuestions.indexOf(questionIndex);
      // remove the questionIndex from the availableQuestions array, so that the question does not repeat
      availableQuestions.splice(index1,1);
      //console.log(questionIndex)
      //console.log(availableQuestions)
  
  
      //set options
      //get the length of options
     const optionLen =  currentQuestion.options.length
     //push options into availableOptions array
     for (let i=0; i&lt;optionLen; i++){
          availableOptions.push(i)
     }
      optionContainer.innerHTML = '';
     let animationDelay = 0.15;
     //create options in html
     for(let i=0; i&lt;optionLen; i++){
          //random options
          const optionIndex = availableOptions[Math.floor(Math.random() * availableOptions.length)];
          //get the position of optionIndex from the availableOptions
          const index2 = availableOptions.indexOf(optionIndex);
          //remove the optionIndex from availableOptions
          availableOptions.splice(index2,1);
          const option = document.createElement("div");
          option.innerHTML = currentQuestion.options[optionIndex];
          option.id = optionIndex;
          option.style.animationDelay= animationDelay + 's';
          animationDelay = animationDelay + 0.15;
          option.className = "option";
          optionContainer.appendChild(option)
          option.setAttribute("onclick", "getResult(this)");
     }
      questionCounter++
  }
  //get result of current attempt
  function getResult(element){
      const id = parseInt(element.id);
      //get the answer by compairing the id of the options
      if (id === currentQuestion.answer){
          //set the green color to the correct option
          element.classList.add("correct");
          //add color to indector if answer is correct
          updateAnswerIndecator("correct");
          correctAnswers++;
  
      }else{
          //set the red color to the incorrect option
          element.classList.add("wrong");
          //add color to indector if answer is wrong
          updateAnswerIndecator("wrong");
      }
      attempt++;
      //unclickableOptions();
  }
  
  /*make all options unclickable once the user select
  function unclickableOptions(){
      const optionLen = optionContainer.children.length;
      for(let i=0 ; i&lt;optionLen ; i++){
          optionContainer.children[i].classList.add("aready-answered");
      }
  }*/
  
  function answerIndecator(){
      answerIndecatorContainer.innerHTML = '';
      const totalQuestion = quiz.length;
      for (let i=0 ; i&lt;totalQuestion ; i++){
          const indecator = document.createElement("div");
          answerIndecatorContainer.appendChild(indecator);
      }
  } function updateAnswerIndecator(markType){
      answerIndecatorContainer.children[questionCounter-1].classList.add(markType);
  }
  
  function next(){
      if (questionCounter === quiz.length){
  
          quizOver();
      }else{
          getNewQuestions();
      }
  //
  
  }
  
  //Previous button
  /*function previous(){
      if (questionCounter == 0) {
         questionCounter = quiz.length - 1;
       } // reset question
       else {
         questionCounter--;
       }
  }*/
  //
  function quizOver(){
      //when the quiz is over, the  timer stops
  //window.clearInterval(update);
  clearInterval(countdownTimer);
    upgradeTime = "-";
      //show the registrer box
      registerBox.classList.remove("hide");
      //hide quiz box
      quizBox.classList.add("hide");
  
  }
  
  function register(){
      //show the result box
      resultBox.classList.remove("hide");
      //
      registerBox.classList.add("hide");
      quizResult();
  }
  
  //get the quiz result
  function quizResult(){
      resultBox.querySelector(".total_question").innerHTML = quiz.length;
      resultBox.querySelector(".total_attempt").innerHTML = attempt;
      resultBox.querySelector(".total_correct").innerHTML = correctAnswers;
      resultBox.querySelector(".total_wrong").innerHTML = attempt - correctAnswers;
      const persentage = (correctAnswers/quiz.length)*100;
      resultBox.querySelector(".persentage").innerHTML = persentage.toFixed(2) + "%";
      resultBox.querySelector(".total_score").innerHTML = correctAnswers + " / " + quiz.length;
  }
  
  function resetQuiz(){
       questionCounter = 0;
       correctAnswers = 0;
       attempt = 0;
  
  }
  
  function tryAgainQuiz(){
      //hide the resultBox
      resultBox.classList.add("hide");
      //show the quizBox
      quizBox.classList.remove("hide");
  
      resetQuiz();
      startQuiz();
  }
  
  function goToHome(){
      //hide the result box
      resultBox.classList.add("hide");
      //show home box
      homeBox.classList.remove("hide");
  
      resetQuiz();
  }
  //###STARTING POINT###
  
  function startQuiz() {
      //start timer
      upgradeTime = 20;
      seconds = upgradeTime;
      //hide home Box
      homeBox.classList.add("hide");
      //show the quiz box
      quizBox.classList.remove("hide");
      //first we set all questions in availableQuestions array
      setAvailableQuestions();
      //second we will call the getNewQuestions() funcrion
      getNewQuestions();
      //to create indecator of answers
      answerIndecator();
  
  }
  function timer() {
  var days        = Math.floor(seconds/24/60/60);
  var hoursLeft   = Math.floor((seconds) - (days*86400));
  var hours       = Math.floor(hoursLeft/3600);
  var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
  var minutes     = Math.floor(minutesLeft/60);
  var remainingSeconds = seconds % 60;
  function pad(n) {
  return (n &lt; 10 ? "0" + n : n);
  }
  document.getElementById('countdown').innerHTML = "الوقت المتبقي :" + pad(minutes) + ":" + pad(remainingSeconds);
  if (seconds == 0) {
  clearInterval(countdownTimer);
  document.getElementById('countdown').innerHTML = "انتهى الوقت";
  quizBox.classList.add("hide");
  registerBox.classList.remove("hide");
  
  //show the result box
  /*resultBox.classList.remove("hide");
  quizResult();*/
  
  } else {
  seconds--;
  }
  }
  var countdownTimer = setInterval('timer()', 1000);
  window.onload = function (){
      homeBox.querySelector(".total_question").innerHTML = quiz.length;
  }
  
  
  //array of objects
  const quiz = [
      {
          q:' أوجد قيمة: \(\left( {3 + \sqrt 3 } \right) - \sqrt 3  + 18\) ',
          options:['٨٤','\(81 + \sqrt 6 \)','٧٨','٧٩'],
          answer:0
      },
      {
          q:' HOW',
          options:['٣٤,١ دقيقة ','٣,١٤ دقيقة ','٣١٤ دقيقة','٣٤١ دقيقة '],
          answer:0
      },
      {
          q:'ا قيمة  \(\frac{{{9^4} - {9^6}}}{{{9^2} - {9^3}}}\) ',
          options:['800','810','9','\({9^3}\)'],
          answer:0
      },
      {
          q:'ذا كانت مساحة الدائرة الصغيرة = 16 ط فإن محيط المنطقة المظللة = ',
          options:['64 ط','4ط','8ط','24'],
          answer:3
      },
      {
          q:'حتاج ارض زراعية 15 يوم لينمو فيها  \(1.2 + {10^8}\) من لا شيء فكم تحتاج لينمو فيها  \(4.0 + {10^8}\) من لا شيء',
          options:['18','60','13','45'],
          answer:1
      },
      {
          q:'حتاج ارض زراعية 15 يوم لينمو فيها  \(1.2 + {10^8}\) من لا شيء فكم تحتاج لينمو فيها  \(4.0 + {10^8}\) من لا شيء',
          options:['18','60','13','45'],
          answer:1
      }
  ]</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;0,700;1,700&amp;display=swap');
  body{
      margin: 0;
      font-size: 16px;
      background-color: #009688;
      font-family: 'Montserrat', sans-serif;
      font-weight: 400;
  }
  
  *{
      box-sizing: border-box;
      margin:0;
      padding:0;
      outline:none;
  }
  
  .custom_box{
      max-width: 700px;
      background-color: #ffffff;
      margin: 49px auto;
      padding: 30px;
      border-radius: 10PX;
      animation: fadeInRight 1s ease;
  }
  @keyframes fadeInRight{
      0%{
          transform: translateX(40px);
          opacity: 0;
      }
      100%{
          transform: translateX(0px);
          opacity: 1;
      }
  }
  .custom_box::before,
  .custom_box::after{
      content: '';
      clear: both;
      display: table;
  }
  
  .custom_box.hide{
      display: none;
  }
  
  .home_box h3{
      font-size: 18px;
      color:#000000;
      font-weight:500;
      margin-bottom: 15px;
      line-height: 25px; 
  }
  
  .home_box p{
      font-size: 16px;
      margin-bottom: 10px;
      line-height:22px;
      color:#000000;
      font-weight:400;
  }
  
  .home_box p span{
      font-weight: 500;
  }
  
  .home_box .btn{
      margin-top: 20px; 
  }
  
  .btn{
      padding: 15px 45px;
      background-color: #009688;
      color: #ffffff;
      border:none;
      border-radius:5px;
      font-family: 'Montserrat', sans-serif;
      font-size:16px;
      cursor:pointer;
      display: inline-block;
  }
  
  .quiz_box .question_number,
  .quiz_box .question_text,
  .quiz_box .option_container,
  .quiz_box .next_question_btn,
  .quiz_box .answer_indicator{
      width: 100%;
      float: left;
  }
  
  .quiz_box .question_number{
      font-size: 18px;
      color:#009688;
      font-weight: 600;
      border-bottom: 1px solid #cccccc;
      padding-bottom: 10px;
      line-height: 25px;
  }
  
  .quiz_box .question_text{
      font-size: 22px;
      color:#000000;
      line-height: 28px;
      font-weight: 400;
      padding: 20px 0;
      margin: 0; 
  }
  
  
  .quiz_box .option_container .option{
      background-color: #cccccc;
      padding:13px 15px;
      font-size: 16px;
      line-height: 22px;
      color: #000000;
      border-radius: 5px;
      margin-bottom: 10px;
      cursor: pointer;
      text-transform: capitalize;
      opacity: 0;
      animation: fadeIn 0.3s ease forwards;
      position: relative;
      overflow: hidden;
  }
  .quiz_box .option_container .option.aready-answered{
      pointer-events: none;
  }
  @keyframes fadeIn{
      0%{
          opacity: 0;
      }
      100%{
          opacity: 1;
      }
  }
  .quiz_box .option_container .option.correct::before{
      content: '';
      position: absolute;
      left:0;
      top: 0;
      height: 100%;
      width: 100%;
      background-color: green;
      z-index: -1;
      animation: slideInLift .5s ease forwards
  }
  @keyframes slideInLift{
      0%{
          transform: translateX(-100%);
      }
      100%{
          transform: translateX(0%);
      }
  }
  .quiz_box .option_container .option.correct{
      color: #ffffff;
  }
  .quiz_box .btn{
      margin: 15px 0;
  }
  
  .quiz_box .answer_indicator{
      border-top: 1px solid #cccccc;
  
  }
  
  .quiz_box .answer_indicator div{
      height: 40px;
      width: 40px;
      display: inline-block;
      background-color: #cccccc;
      border-radius: 50%;
      margin-right:3px;
      margin-top: 15px;
  }
  
  .quiz_box .answer_indicator div.correct{
      background-color: green;
  }
  .quiz_box .answer_indicator div.wrong{
      background-color: red;
  }
  .result_box{
      text-align: center;
  }
  
  .result_box.hide{
      display: none;
  }
  
  .result_box h1{
      font-size: 36px;
      line-height: 42px;
      color: #009688;
  }
  .result_box table{
      width: 100%;
      border-collapse: collapse;
      margin:30px 0;
  }
  .result_box table td{
      border:1px solid #cccccc;
      padding: 8px 15px;
      font-weight: 500;
      color: #000000;
      width: 50%;
      text-align: left;
      font-size: 18px;
  }
  .result_box .btn{
      margin-right: 20px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;&lt;/title&gt;
      &lt;link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"&gt;
      &lt;link rel="stylesheet" type="text/css" href="random_style.css"&gt;
  &lt;/head&gt;
  &lt;body&gt;
     &lt;div class="home_box custom_box"&gt;
      &lt;h3&gt;هذا الاختبار يحتوي على ٢٥ سؤال بمدة ٢٥ دقيقة&lt;/h3&gt;
      &lt;p&gt;عدد الأسئلة: &lt;span class="total_question"&gt;&lt;/span&gt;&lt;/p&gt;
      &lt;button type="button" class="btn" onclick="startQuiz()"&gt;ابدأ الاختبار &lt;/button&gt;
     &lt;/div&gt;
  
              &lt;div class="time_box custom_box "&gt;
              &lt;span id="countdown" class="timer"&gt;&lt;/span&gt;
                        &lt;!-- &lt;text&gt;الوقت المتبقي: &lt;text id="time001"&gt;1200&lt;/text&gt;&lt;/text&gt;&lt;br/&gt;--&gt;
              &lt;/div&gt;
   &lt;div class="quiz_box custom_box hide"&gt;
          &lt;div class="question_number"&gt;
  
          &lt;/div&gt;
          &lt;div class="question_text"&gt;
  
          &lt;/div&gt;
          &lt;div class="option_container"&gt;
  
          &lt;/div&gt;
          &lt;div class="next_question_btn"&gt;
  &lt;button type="button" class="btn" onclick="next()"&gt;التالي&lt;/button&gt;
          &lt;!--    &lt;button type="button" class="btn" onclick="previous()"&gt;السابق&lt;/button&gt;--&gt;
  
  
          &lt;/div&gt;
          &lt;div class="answer_indicator"&gt;
  
          &lt;/div&gt;
   &lt;/div&gt;
   &lt;div class="register_box custom_box hide" style="direction: rtl;"&gt;
      &lt;form &gt;
          &lt;p&gt;الرجاء ادخال بياناتك للحصول على نتيجة اختبارك &lt;/p&gt;&lt;br&gt;
  
          &lt;label for="uname"&gt;اسمك الكامل &lt;br&gt;&lt;/label&gt;
          &lt;input type="text"  class="w3-input w3-border w3-round-large" placeholder="ادخل اسمك الكامل " name="uname" required&gt;&lt;br&gt;
  
     &lt;label for="email"&gt;الايميل &lt;br&gt;&lt;/label&gt;
     &lt;input type="email"  class="w3-input w3-border w3-round-large" placeholder="ادخل اسمك الكامل " name="email" required&gt;&lt;br&gt;
  
     &lt;label for="phone"&gt;رقم الجوال (اختياري )&lt;br&gt;&lt;/label&gt;
     &lt;input type="number"  class="w3-input w3-border w3-round-large" placeholder="ادخل رقم الجوال " name="phone"&gt;&lt;br&gt;
         &lt;button type="button" value="submit" onclick="register()"class="btn"&gt;تسجيل &lt;/button&gt;
  
      &lt;/form &gt;
   &lt;/div&gt;
  
   &lt;div class="result_box custom_box hide"&gt;
          &lt;h1&gt;النتيجة&lt;/h1&gt;
          &lt;table&gt;
              &lt;tr&gt;
                  &lt;td&gt; total questions&lt;/td&gt;
                  &lt;td&gt;&lt;span class="total_question"&gt;&lt;/span&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;attempt&lt;/td&gt;
                  &lt;td&gt;&lt;span class="total_attempt"&gt;&lt;/span&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;correct&lt;/td&gt;
                  &lt;td&gt;&lt;span class="total_correct"&gt;&lt;/span&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;wrong&lt;/td&gt;
                  &lt;td&gt;&lt;span class="total_wrong"&gt;&lt;/span&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;persentage&lt;/td&gt;
                  &lt;td&gt;&lt;span class="persentage"&gt;&lt;/span&gt;&lt;/td&gt;
              &lt;/tr&gt;
              &lt;tr&gt;
                  &lt;td&gt;your total score&lt;/td&gt;
                  &lt;td&gt;&lt;span class="total_score"&gt;&lt;/span&gt;&lt;/td&gt;
              &lt;/tr&gt;
          &lt;/table&gt;
          &lt;button type="button" class="btn" onclick="tryAgainQuiz()"&gt;try again&lt;/button&gt;
          &lt;button type="button" class="btn" onclick="goToHome()"&gt;go to home&lt;/button&gt;
   &lt;/div&gt;
  
  &lt;script src="quistion.js" charset="utf-8" type="text/javascript"&gt;&lt;/script&gt;
  &lt;script src="app.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>