I am quite new to javascript. Any help very appreciated.
I have created a simplified example for easier explanation. I want to change a finalArray
according to whether the checboxes are checked or unchecked.
So for example if friends
and strangers
checkboxes are checked then the finalArray_
should = ["friend1" ,"friend2", "stranger1", "stranger2"]
.
If only enemies
checkbox is checked then the finalArray_
should = ["enemy1" ,"enemy2"]
. And so on.
<body>
<input type="checkbox" data-id="friends_"> Friends <br />
<!-- other code and functionality -->
<input type="checkbox" data-id="enemies_"> Enemies <br />
<!-- other code and functionality -->
<input type="checkbox" data-id="strangers_"> Strangers <br />
<script>
const friends_ = ["friend1","friend2"];
const enemies_ = ["enemy1","enemy2"];
const strangers_ = ["stranger1","stranger2"];
</script>
</body>
I tried this, but I know it's a crappy solution that doesn't work because I can't concat a string like this.
<script>
const friends_ = ["friend1", "friend2"];
const enemies_ = ["enemy1", "enemy2"];
const strangers_ = ["stranger1", "stranger2"];
const checkboxes = document.querySelectorAll("input[type=checkbox]");
checkboxes.forEach(function (checkbox) {
checkbox.addEventListener('change', function () {
checked_boxes = Array.from(checkboxes).filter(i => i.checked).map(i => i.dataset.id).join();
const finalArray = [].concat(checked_boxes);
console.log(finalArray); //Array [ "friends_,strangers_" ]
})
})
</script>
Thanks for your suggestions.
Aucun commentaire:
Enregistrer un commentaire