i am trying to create a delete method using fetch API, on when i click on the first row of the table the javaScript function works but if i click on any other column that is not the first one, the function doesn't work.
the script function :
<script>
var trashcan = document.querySelectorAll('a.delete_category_a');
for (let i = 0; i < trashcan.length; i++) {
trashcan[i].addEventListener("click", function() {
const url = `/halalMunchies/delete-category/${trashcan.dataset.doc}`;
fetch(url, {
method: 'DELETE'
})
.then((response) => response.json())
.then((data) => window.location.href = data.redirect)
.catch(err => console.log(err));
});
}
</script>
the delete function in the controller :
exports.deleteCategory = (req, res, next) => {
console.log('DELETE CATEGORY /delete-category');
const id = req.params.id;
categorySchema.findByIdAndDelete(id)
.then(result => {
res.json({ redirect: '/halalMunchies/all-categories' });
})
.catch(err => {
console.log(err);
});
};
the ejs file table
<tr>
<% categoryiesList.forEach(function (category) {%>
<td>
<%=category.categoryName %>
</td>
<td>
<center> <a href="<%=`/halalMunchies/update-category/${category._id}`%>" style="color: green"> Edit </a> </center>
</td>
<td>
<center> <a type="button" class="delete_category_a" data-doc="<%=category._id%>" style="color: red "> Delete </a> </center>
</td>
</tr>
<%})%>
that error occurs when i click on the delete tag to run the eventlistner and it refers to the the >>
const url = `/halalMunchies/delete-category/${trashcan.dataset.doc}`;
Error on the webConsole :
Uncaught TypeError: Cannot read properties of undefined (reading 'doc')
at HTMLAnchorElement.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…