user10255954
user10255954

Reputation:

Concatenation using for loop Javascript

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;
}

Upvotes: 0

Views: 62

Answers (3)

sham247
sham247

Reputation: 41

Firstly , you need to optimize that code , don't hard code everything , add a single tag in a loop and render that.( Just a Suggestion )

Secondly , why even access all the input elements by accessing the DOM , you could easily get them through the Form you appended on the top. When you attach a Form to a group of Input Tags , it stores those instances in the Form itself , simply get the Form ( you could attach an ID to that ) and access all the inputs through that instance.

Upvotes: 1

Waleed Ahmad
Waleed Ahmad

Reputation: 494

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.

Upvotes: 1

Invizi
Invizi

Reputation: 1298

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>

Upvotes: 1

Related Questions