I have an ejs page that uses some data including a loop through <%= items[i].id %> and buttons adding or deleting items. Once I transfer delete functionality into a bootstrap modal (creating a delete confirmation dialogue) the loop stops working and only the first array item gets deleted. I'm using Bootstrap 4.0 and their built-in JQuery. Deleting works correctly if performed outside the modal. Thank you for any hints!
<% for (let i=0; i<items.length; i++) { %>
<div class="card w-100 p-3">
<form method="post" >
<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="card-header">
<%= items[i].name %>
</div>
<div class="card-body">
<p class="card-text"> <%= items[i].desc %> </p>
</div>
<button formaction="/project" type="submit" class="btn btn-outline-dark" name="editButton" value="<%= items[i].id %>">Edit</button>
<button type="button" class="btn btn-outline-danger" data-toggle="modal" data-target="#deleteModal">Delete</button>
</div>
</form>
</div>
<!-- Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<form class="form-control" action="/delete" method="post">
<p>Are you sure you want to delete <%= items[i].name %> ? </p>
<button type="submit" class="btn btn-outline-danger" name="deleteButton" value="<%= items[i].id %>">Delete</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</form>
</div>
</div>
</div>
</div>
<% } %>
All <div class="model...
have the same id
attribute. Wwhen you click on delete button just the first modal is opened. Add <%= i %>
as suffix on id
:
<% for (let i=0; i<items.length; i++) { %>
<div class="card w-100 p-3">
<form method="post">
...
<button data-target="#deleteModal<%= i %>" type="button" class="btn btn-outline-danger" data-toggle="modal" >Delete</button>
</form>
</div>
<!-- Delete Modal -->
<div id="deleteModal<%= i %>" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
...
</div>
<% } %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.