I have an array of 10 elements. At first I want to shuffle the array elements and display them (my current code does this). Then I want to show an alert message if any of the displayed array elements are clicked. This is the thing I am having problem with. If, I am doing onclick, it's showing me only 1 array element instead of all the 10 array elements and also showing the following error in console Uncaught TypeError: Cannot set property 'onclick' of undefined. My code is (I am using only javascript):
<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>
onclickhandler with it. You need to create an actual tag.