samedi 15 mai 2021

How can I push array values checked in checkboxes made from a for loop to another array?

for the purpose of what I am doing I used a for loop to create check boxes from a previous array instead of doing it through html. This loop takes the object's .name value from the players array and displays it as a checkbox that can be checked if that player wants to play.

let playing = [];//8 players maximum

//array displayed as check boxes
var players = [
  {"name": "Tyler", "score": 4},
  {"name": "Nick", "score": 4},
  {"name": "Patrick score 3", "score": 3},
  {"name": "Jack", "score": 3},
  {"name": "Aboss", "score": 3},
  {"name": "Colin", "score": 1}, 
  {"name": "Sling", "score": 1},
  {"name": "Joe", "score": 2},
  {"name": "Terrrence", "score": 2},
  {"name": "Scott", "score": 4},
]

//loop to display players[] as checkboxes
var myDiv = document.getElementById("cboxes");

for (var i = 0; i < players.length; i++) {
    var checkBox = document.createElement("input");
    var label = document.createElement("label");
    checkBox.type = "checkbox";
    checkBox.value = players[i];
    myDiv.appendChild(checkBox);
    myDiv.appendChild(label);
    label.appendChild(document.createTextNode(players[i].name));
}

I am having trouble figuring out how to push the objects from the selected boxes to a new array called playing (or the name value at the least) because later I will need to use the .score value associated with the name as well. I would also like to include an error message if more or less than 8 players are selected. I have a single html button:

<button onclick="checkCheckbox()">Push to playing array</button> <br>   

And this is my placeholder function for when the button is pressed:

function checkCheckbox(){
  playing.push(document.getElementById("cboxes"));
}

Thanks fellow nerds




Aucun commentaire:

Enregistrer un commentaire