Reputation: 268265
I want to display a list of items. Each item would have an edit and a delete icon next to it.
For obvious reasons I want to trigger the delete action with HTTP POST.
With jQuery, I would bind links to trigger form.submit
.
However I'm not sure if I should generate a form next to each item or use just one form.
Below are pros and cons of two approaches as I see them.
Form Per Item:
Single Form:
id + '/delete/
).What is there to add? What is the preferred pattern in modern HTML apps?
Upvotes: 1
Views: 133
Reputation: 268265
In the end, I decided to go with AJAX via jQuery.ajax.
The reason is semantically I don't even have forms—I have buttons.
Therefore, jQuery is an easier solution as it allows to keep posting logic in one place (as opposed to scattering it across HTML and JS).
I assigned row
class to each semantical row and put corresponding database IDs in HTML5 data
attribute called data-row-id
for each row.
<div class="row" data-item-id="{{ product.id }}">
<!-- ... --->
<a href="#" class="delete-btn"><img src="/img/delete.png" alt="Delete"></a>
</div>
Then I have something alone the lines of
$('.delete-btn').click(function() {
var row = $(this).closest('.row');
var id = row.data('item-id');
$.ajax({
url: id + '/delete/',
type: 'POST'
});
row.fadeOut().slideUp();
return false;
}
in my $()
load handler.
This solution scales beautifully across the whole codebase because you only have to set row
class and data-item-id
attribute and the buttons will “just work”.
Upvotes: 0
Reputation: 27880
The main disadvantage I see in having a single form enclosing all list elements is that you can end up with a huge POST if the list is long. As an advantage, you could mark multiple elements for deletion (checkboxes, for instance) and perform a single delete request.
I'd go for either
As a side note, you could also skip forms and perform the needed interactions through ajax. This would improve user experience notably. Take into account that forms would still be needed to provide fallback mechanisms in case it was required.
Upvotes: 1
Reputation: 2302
I have used checkboxes in the past. This is better for usability, and each checked checkbox can pass its own ID to the form processing script.
Upvotes: 1