Home > Mobile >  How can I exit for loop in Javascript?
How can I exit for loop in Javascript?

Time:12-03

I want to make it so when user clicks an option on questionnaire they can't click on it again. For that I need to exit from "for loop" (at the end of this code), but when I type in break statement, it's somehow incorrect. Could you tell me the correct way of doing it? Would appreciate the answer very much! :)

<script>
   document.addEventListener("DOMContentLoaded", function() {
       function clicked(answer, i) {
           if (answer[i].value == "correct")
           {
               answer[i].style.backgroundColor = "green";
               let result = "<p>Correct!</p>";
               document.getElementsByClassName("section")[0].insertAdjacentHTML('beforeend', result);
               return;
           }
           else
           {
               answer[i].style.backgroundColor = "red";
               let result = "<p>Wrong!</p>";
               document.getElementsByClassName("section")[0].insertAdjacentHTML('beforeend', result);
               return;
           }
           }
       let answer = document.getElementsByTagName('button');
       for (let i = 0; i < answer.length; i  ) {
           answer[i].addEventListener("click", () => {
           {
               clicked(answer, i);
           }
       });
       }
       });
</script>

CodePudding user response:

Your logic is wrong...

Your for loop is setting the click event on all your answers, breaking it would just mean you wouldn't add the event on all the answers.

What you need to do is either :

  • remove the click event on all the answers AFTER the first click (in your clicked() function)
  • set a true/false "hasBeenClickedOn" flag that you'll check at the beginning of you clicked() function

For example :

<script>

    var hasBeenClickedOn = false; // global flag

   document.addEventListener("DOMContentLoaded", function() {
       function clicked(answer, i) {
       
            if (hasBeenClickedOn===true) { return false; } // check the flag       
            hasBeenClickedOn = true; // set the flag       
       
           if (answer[i].value == "correct")
           {
               answer[i].style.backgroundColor = "green";
               let result = "<p>Correct!</p>";
               document.getElementsByClassName("section")[0].insertAdjacentHTML('beforeend', result);
               return;
           }
           else
           {
               answer[i].style.backgroundColor = "red";
               let result = "<p>Wrong!</p>";
               document.getElementsByClassName("section")[0].insertAdjacentHTML('beforeend', result);
               return;
           }
           }
       let answer = document.getElementsByTagName('button');
       for (let i = 0; i < answer.length; i  ) {
           answer[i].addEventListener("click", () => {
           {
               clicked(answer, i);
           }
       });
       }
       });
</script>
  • Related