Search code examples
htmlformshtml-tablew3c-validation

How to handle multiple <form>s in a single table and have HTML validate


It seems that I cannot have two forms embedded into a single table AND have my HTML validate. For example, the W3 Validator gives me

Element <form> not allowed as child of element <tr> in this context.

I don't see a way to go around validation errors.

What I want to achieve is this:

  • In an HTML table "row" I have and can change some input values and then use my "Save" button at the end of the row, to save them
  • If I have to delete a row, I can do so by pressing Delete button.
  • UI-wise it makes sense to me to have two forms, one each for Save/Delete button, per row.
  • I can have several rows, each row with its own Save/Delete button

Example UI

Numbers are input fields and save/delete are buttons. enter image description here

My simplified non-conforming HTML below:

<!DOCTYPE html>
<html>
<head>
<title>HTML</title>
</head>
<body>
<table>

<tr>
    <form>
    <td><input type="text" name="row_id" value="1"></td>
    <td><input type="text" name="five" value="5"></td>
    <td><input type="text" name="three" value="3"></td>
    <td><input type="submit" value="Save This Row"></td>
    </form>

    <td><form>
            <input type="text" name="row_id" value="1">
            <input type="submit" value="Delete This Row">
    </form></td>
</tr>
</table>

</body>
</html>

HTML works surprisingly, but it does not validate. I am seeking a solution where it does both - work and validate.


Solution

  • You have several options:

    1. Keep your code as is. It’s invalid, but it works. It might fail in some future browsers, but that’s not probable.
    2. Reorganize the code so that all fields are in one form and put the entire table inside that form. This probably requires changes to the server-side form handler and may require changes to HTML too.
    3. Reorganize it so that you have a two-column table, with the first column containing forms that contain inner one-row tables. This requires that you explicitly set the column widths of the inner tables to make the whole look like one table.
    4. Put the Save buttons in forms (inside the cell) and refer to those forms from the input buttons with the form attribute. This way each form would be inside one cell and it would be connected with input elements outside it with those attributes. This would be the cleanest solution, but the form attribute is not supported by IE.