It has come to my attention that users are able to submit answers without actually making any selections from a menu of buttons. This results in an empty array being printed to the console, which is not the intended behavior.
I am seeking a solution that will prevent users from submitting answers without first selecting options from the menu. The array should always contain either A, B, C, or D, or a combination of these letters. If a user attempts to submit without making any selections, they should receive an error message.
I am facing difficulties implementing this functionality, as the buttons are generated dynamically using a map function based on a list. Any advice on how to achieve this would be greatly appreciated. Thank you!
<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 $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');
clicked = [];
// 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() {
console.log('clicked array', clicked);
$(".buttons").css({
backgroundColor: 'transparent'
});
$(".buttons").removeClass('selected');
// reset clicked list after recording button selections
clicked = [];
}
</script>
</body>
</script>
</html>