I have a menu of buttons and am trying to record which buttons a user selects. The user can select multiple buttons before they submit their answer by clicking on the done button. They can change their mind by unclicking selections, but their final answer should be submitted upon clicking the done button.
Currently, I'm able to record multiple button selections by pushing to an array upon each click. However, if a user unclicks a button, I have not been able to figure out how to update my array. For example, if a user clicks A, B, A. It will unselect A, but the array still records ["A", "B"] when it should instead record ["B"]. Does anyone what I am doing wrong?
It's unclear to me whether selections are recorded based on clicks or buttons have the class 'selected' from (let syms = document.querySelectorAll('.selected'). Many thanks in advance!
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style media="screen">
.buttons {
width: 150px;
height: 50px;
border: solid 2px black;
text-align: center;
color: black;
cursor: pointer;
background-color: white;
margin: 2px;
}
#buttonGallery {
margin: 10px;
padding: 10px;
border: solid 2px black;
width: 155px;
}
#done {
width: 150px;
height: 50px;
border: solid 2px black;
text-align: center;
color: black;
cursor: pointer;
background-color: white;
margin: 2px;
}
</style>
</head>
<body>
<div id="buttonGallery">
<div id="done">
<p>done</p>
</div>
</div>
<script type="text/javascript">
let $buttonGallery = $("#buttonGallery");
let myList = ["A", "B", "C", "D"];
let myColors = ["red", "green", "blue", "red"];
let clicked = [];
myList.map(function(letter, index) {
let clicked = [];
let $button = $("<div></div>")
.addClass("buttons")
.attr("id", "button_" + letter)
.html("<p>" + letter + "</p>")
.on("mouseenter", function() {
$(this).css("background", myColors[index]);
})
.on("mouseleave", function() {
if (!$(this).hasClass('selected')) {
$(this).css("background", "transparent");
}
})
.on("click", function() {
$(this).css("background", myColors[index]);
$(this).toggleClass('selected');
// push clicked variables to array
let syms = document.querySelectorAll('.selected');
for (let n = 0; n < syms.length; n++) {
if (!clicked.includes(syms[n].textContent)) {
clicked.push(syms[n].textContent);
}
};
// send data to server
console.log('clicked array', clicked);
})
$("#done").before($button);
});
$("#done").on("click", clearColor);
function clearColor() {
$(".buttons").css({
backgroundColor: 'transparent'
});
$(".buttons").removeClass('selected');
// reset clicked list
clicked = [];
}
</script>
</body>
</script>
</html>
clicked = [];before "// push clicked variables to array" and try...