I am using EJS, express and axios to pushing over an array called `data` containing all the data to be rendered. I am looping over the data array to render it and that’s working.
The problem is I want to be able to click on each item and then pass over the key or index of that item to another element, so I can render that element with the data of with that specific index. When I click on one of the items though, I get a error saying data is not defined in the browser console.
I am guessing that is probably because it can’t see the variables from the script tag but I tried some other ways and it just would update the data.
Can somebody help me with this problem?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/styles/globals.css">
<link rel="stylesheet" href="/styles/main.css">
</head>
<body>
<% let showing = 0 %>
<div class="box grid">
<div class="container_1">
<% for(let i = 0; i < data.length; i++){ %>
<div class="item" onclick="setShowing(this.getAttribute('key'), data)" key="<%= i %>">
<h2><%= data[i].name %></h2>
<p><%= data[i].gender %>, <%= data[i].nationality %>, <%= data[i].age %></p>
</div>
<% } %>
</div>
<div class="container_2">
<div class="item_details">
<h2><%= data[showing].name %></h2>
<p><%= data[showing].gender %>, <%= data[showing].nationality %>, <%= data[showing].age %></p>
</div>
</div>
</div>
<script>
function setShowing(newValue, data) {
console.log("updating value:", newValue);
showing = newValue;
const nameElement = document.querySelector('.item_2 .item h2');
const detailElement = document.querySelector('.item_2 .item p');
nameElement.innerHTML = data[showing].name;
detailElement.innerHTML = data[showing].gender + ", " + data[showing].nationality + ", " + data[showing].age;
}
</script>
</body>
</html>
I was expecting for it to render the data with the index stored in the variable showing
. Instead it gave me an error saying it’s not defined.
I also tried doing it another way and it would give me an error, but then it wouldn’t update any of the data.
Ludwig is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.