I am working with an array of 10 elements that I need to shuffle and display, which my current code is able to do. However, the issue arises when I try to add functionality to show an alert message if any of the displayed array elements are clicked. The problem I am facing is that when using onclick, it only shows one array element instead of all 10, and also throws an error in the console: Uncaught TypeError: Cannot set property 'onclick' of undefined. Below is the JavaScript code I am currently using:
<script>
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var myArray = ['1','2','3','4','5','6','7','8','9','10'];
newArray = shuffleArray(myArray);
for (i=0;i<newArray.length;i++) {
var p = document.write(newArray[i] + "<br >");
p.onclick = showAlert; // this is showing me only 1 array element and also showing error in concole
}
function showAlert() {
alert("onclick Event detected!")
}
</script>