After creating a function that saves checked values in the 'Arr' array, I am facing an issue where the array is being printed multiple times when the "View Results" button is clicked. This results in the checked values appearing multiple times on the screen when displayed in HTML. Is there a way to ensure that the result is printed only once when the button is clicked?
const list = Array.from(document.querySelectorAll(".form"));
const Arr = [];
const submitBtn = document.querySelector('.submit-button');
function check(e) {
// a) When checked display result in array
if (e.target.checked) {
Arr.push(`${e.target.value}`);
// b) When unchecked remove result from array
} else if (!e.target.checked) {
let index = Arr.indexOf(e.target.value);
if (index != -1) {
Arr.splice(index, 1)
}
}
submitBtn.addEventListener('click', function() {
console.log(Arr);
})
}
list.forEach(function(listItems) {
listItems.addEventListener('change', check)
})
<form class="form">
<p> <u> Once you've checked the values below, check console to see value </u> </p>
<br>
<div class="list-items">
<input type="checkbox" value="Item-1">Item-1
<br>
<input type="checkbox" value="Item-2">Item-2
<br>
<input type="checkbox" value="Item-3">Item-3
<br>
<input type="checkbox" value="Item-4">Item-4
<br>
<input type="checkbox" value="Item-5">Item-5
<br>
<input type="checkbox" value="Item-6">Item-6
<br>
<input type="checkbox" value="Item-7">Item-7
</div>
<div class="form submit">
<h3 class="submit-message">Please click "View Results" to see your checked values in the console.
<br>
<button class="submit-button"><a href="#">View Results</a></button>
</h3>
</div>