开发者

Should I use one form on page or generate a form per item?

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.

Belo开发者_Python百科w are pros and cons of two approaches as I see them.

Form Per Item:

  • easy to generate;
  • no need to fiddle in JS to set action and input value.

Single Form:

  • makes more sense semantically;
  • requires client JS to set hidden input;
  • requires client JS to set form action (e.g. id + '/delete/).

What is there to add? What is the preferred pattern in modern HTML apps?


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.


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

  1. A single form for each list element. This would make deletion of multiple elements impossible, but would keep POST sizes minimal.
  2. Using a single form, but in a way that doesn't include all the list elements. For instance, having a delete only form with a single hidden element in it, into which you would put all the id's marked for deletion with JS manipulation.

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.


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”.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜