Beginner here. I have an HTMl table with buttons and I want a button to toggle open a form with the values from that row. Problem is, if I have multiple rows in my table, it opens multiple forms for each row with the values pre-filled. How can I make it so that it only opens a single form for that row only?
my HTML and js , shortened for clarity
I have already gone from IDs to classes, but still it wouldn’t work.
$(".btn-edit-address").click(function() {
$('.form-edit-address').toggle('fast');
});
function closeEditAddressForm() {
$('.form-edit-address').toggle('fast');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="table-responsive my-5">
<table id="table-address-book" class="display table table-striped table-hover">
<thead>
<tr style="text-align: center;">
<th style="width: 150px;">insert headers here</th>
<th style="width: 150px;">Actions</th>
</tr>
</thead>
<tbody>
{% for address in addressInfo %}
<tr class="row-address-book" style="text-align: center; vertical-align: middle;">
<td>
insert table data here
</td>
<td>
<div class="d-flex align-items-center justify-content-center" style="display: inline; vertical-align: baseline;">
<button class="btn btn-sm mx-1 btn-black" type="button" hidden="">
<i class="fa fa-chevron-down"></i>
</button>
<button class="btn-edit-address btn btn-sm mx-1" type="button" style="color: rgb(24, 115, 184);">
<i class="fa fa-edit"></i>
</button>
<form action="{{ url_for('homepage.deleteBuyerAddress', addressBookID=address.0 ) }}" class="form-delete-address" method="POST">
<button class="btn-delete-address btn btn-sm mx-1" type="submit" style="color: red;">
<i class="fa fa-times"></i>
</button>
</form>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% for address in addressInfo %}
<form action="#" method="POST" class="form-edit-address" style="display: none; margin-top: 50px;">
<div class="input-group mb-3">
input groups here
</div>
<div class="d-flex align-items-center justify-content-center">
<button class="btn btn-primary me-2" type="submit" style="margin-top: 25px;">
Edit address
</button>
<button class="btn btn-warning ms-2" type="button" style="margin-top: 25px;" onclick="closeEditAddressForm()">
Cancel
</button>
</div>
</form>
{% endfor %}
2
Answers
With your current structure, it seems that you’ll need a way to associate each table row (or button) with its corresponding form. It looks like each row has the same numeric index as its form (i.e. row#1 corresponds to form#1, row#2 to form#2, etc.), so you might consider using jQuery’s
index()
andeq()
. You could also assign each table row (or button) a data attribute that matches the data attribute or unique ID of its corresponding form.Here’s an example using
index()
andeq()
:Here’s an example using data attributes and IDs:
You can delegate and have only one form
Store the ID in the row as a data attribute and use that to tell the server what ID you are targeting