I have a EJS template which gets included on a page by running a for loop. Each template has a link which when clicked should toggle the display/hiding of a number of checkboxes. I am trying to use AJAX and have a javascript file which is linked to the template. In this javascript file I add an eventlistener to the link on that template. However only the link on the first template on the page fires.
The EJS template:
<link rel="stylesheet" href="../css/categorieslist.css">
<article class="post-item" id="<%= user.UserID %>" data-userId="<%= user.UserID %>">
<p>
<%= user.Email %>
<input type="hidden" class="hiddenField" id="userid" name="userid" value="<%= user.UserID %>" required>
<p><%= user.UserID %></p>
<a class="btn catbtn" href="/admin-usercategories/<%= user.UserID %>/edit">Edit Call</a>
<div class="categorieslist">
<% for (const cat of categories) { %>
<p>
<input type="checkbox" id="<%= cat.CategoryID %>" value="<%= cat.CategoryID %>">
<label for="<%=cat.CategoryID %>"><%= cat.CategoryName %></label>
</p>
<% } %>
</div>
</p>
</article>
<script type="text/javascript" src="/javascript/usercategories.js" charset="utf-8"></script>
The javascript file:
const btn = document.querySelector(".catbtn");
const displayElement = document.querySelector(".categorieslist");
btn.addEventListener('click', function() {
fetchUserCategories();
});
async function fetchUserCategories() {
if (displayElement.style.display === "none") {
displayElement.style.display = "block";
} else {
displayElement.style.display = "none";
}
}