Home > other >  Concatenation using for loop Javascript
Concatenation using for loop Javascript

Time:09-23

I have to add values for all the checkbox that are selected. I would like to use a for loop to achieve this.

But the code is not working and I believe it's because of the way that I am doing the concatenation.

I have tried the following but neither works: window.document.forms[2].i.checked == true window.document.forms[2].${i}.checked == true

This is my code:

HTML:

    <form class="jumbotron form3">

        <h5>EXERCICE 7</h5>

        <p>Veuillez cocher trois cases:</p>
        <hr>
        <input type="checkbox" name="1" value="-8"> Case 1
        <br><input type="checkbox" name="2" value="5"> Case 2
        <br><input type="checkbox" name="3" value="3"> Case 3
        <br><input type="checkbox" name="4" value="10"> Case 4
        <br><input type="checkbox" name="5" value="0"> Case 5
        <br><input type="checkbox" name="6" value="-1"> Case 6
        <br><input type="checkbox" name="7" value="-7"> Case 7
        <br><input type="checkbox" name="8" value="15"> Case 8
        <br><input type="checkbox" name="9" value="8"> Case 9
        <br><input type="checkbox" name="10" value="3"> Case 10
        <hr>
        <input type="button" class="btn btn-warning" value="Calculer le score du jeu" onClick="calculerScore()">
        <input type="button" class="btn btn-info" value="Reset">
        <br><br>
        <input type="text" name="score">
    </form>

JS:

calculerScore = () => {
    var resultat = 0;

    for (let i = 1; i <= 10; i  ) {
        if (window.document.forms[2].i.checked == true) {
            resultat  = Number(window.document.forms[2].i.value);
        }
    }

    window.document.forms[2].score.value = resultat;
}

CodePudding user response:

The easy way is by using Array.reduce().

const checkboxes = document.querySelectorAll("input[type=checkbox]");

const result = Array
  .from(checkboxes)
  .reduce((acc, checkbox) => acc   Number(checkbox.value), 0);

console.log(result);
<form class="jumbotron form3">
  <h5>EXERCICE 7</h5>
  <p>Veuillez cocher trois cases:</p>
  <hr>
  <input type="checkbox" name="1" value="-8"> Case 1
  <br><input type="checkbox" name="2" value="5"> Case 2
  <br><input type="checkbox" name="3" value="3"> Case 3
  <br><input type="checkbox" name="4" value="10"> Case 4
  <br><input type="checkbox" name="5" value="0"> Case 5
  <br><input type="checkbox" name="6" value="-1"> Case 6
  <br><input type="checkbox" name="7" value="-7"> Case 7
  <br><input type="checkbox" name="8" value="15"> Case 8
  <br><input type="checkbox" name="9" value="8"> Case 9
  <br><input type="checkbox" name="10" value="3"> Case 10
  <hr>
  <input type="button" class="btn btn-warning" value="Calculer le score du jeu" onClick="calculerScore()">
  <input type="button" class="btn btn-info" value="Reset">
  <br><br>
  <input type="text" name="score">
</form>

CodePudding user response:

You can access your dom elements using querySelector method. We need querySelectorAll since we want to get all matching elements.

Main Steps:

  • Fetches only cases that are checked.
  • Takes their values.
  • Sums these values.
  • Sets final result on score input tag.

Javascript code

const calculerScore = () => {

        // get ONLY checked boxes
        const allCheckedBoxes = window.document.querySelectorAll('input[type=checkbox]:checked');    // returns Nodelist object
        console.log('allCheckedBoxes: ', allCheckedBoxes);

        // take all checked boxes values in seperate array
        const checkedBoxesValues = [...allCheckedBoxes].map(box => {
            return parseInt(box.value);
        })
        console.log("checkedBoxesValues:", checkedBoxesValues)
        
        // sum all values
        let resultat = 0;
        checkedBoxesValues.forEach(value => {
            resultat  = value;
        });
        console.log("resultat: ",resultat);
        
        // finally set value of score input tag
        window.document.querySelector('input[name="score"]').value = resultat;
    }

I have added consoles and comments for understanding.

There is a simpler way to do it with reduce as @Invizi mentioned, However, I have omitted it for now perceiving your understanding of JS.

Let me know if it helped.

  • Related