HTML: table of forms?

2019-01-24 13:48发布

问题:

I frequently find myself wanting to make a table of forms -- a bunch of rows, each row being a separate form with its own fields and submit button. For instance, here's an example pet shop application -- imagine this is a checkout screen which gives you the option to update the quantities and attributes of the pets you've selected and save your changes before checking out:

Pet    Quantity Color Variety   Update
snake         4 black rattle    update
puppy         3 pink  dalmatian update

I would love to be able to do this using HTML that looks like this:

<table> 
<thead><tr><th>Pet</th> <th>Quantity</th> <th>Color</th> <th>Variety</th> <th>Update</th></tr></thead>
<tbody>
     <tr>
          <form>
            <td>snake<input type="hidden" name="cartitem" value="55"></td>
            <td><input name="count" value=4/></td>
            <td><select name="color"></select></td>
            <td><select name="variety"></select></td>
            <td><input type="submit"></td>
          </form>
     </tr>
</tbody>
</table>

This is basically a table full of forms, one form per row. Hitting update once allows you to update that specific row (this is not a real example, my real applications really do require independence of rows).

But this is not valid HTML. According to spec, a <form> has to be either completely inside a <td> or completely outside a <table>. This invalid html breaks javascript libraries and is a huge pain to deal with.

I end up making one table to contain column headings, and then making one table per form. But this requires fixed column widths to have the inputs lined up in neat columns, which is sub-par. How do you end up dealing with this problem? Is there an obvious easy solution I'm missing? How to I make a table of forms?

回答1:

The trick here is to just use a single form, e.g.

    <form>
      <table>
        <!-- rows... -->
      </table>
      <p><input type="submit" value="Update quantity"></p>
    </form>

Say you have a product snake with id 6. You then name the input for that item's quantity field quantity[6].

I don't know what server side language you are using, but in PHP you can then iterate over the quantites and update based on the ID. You'd get an array like this:

$_POST['quantity'] = array(
    '6' => 4
)


回答2:

You can use css to give table layout to other elements.

.table { display: table; } 
.table>* { display: table-row; }
.table>*>* { display: table-cell; }

Then you use the following valid html.

<div class="table"> 
    <form>
        <div>snake<input type="hidden" name="cartitem" value="55"></div>
        <div><input name="count" value=4/></div>
    </form>
</div>