Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Question -- it seems that I cannot have two forms embedded into a single table AND have my HTML validate. For example, 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.

like image 764
Dennis Avatar asked Nov 25 '14 21:11

Dennis


Video Answer


1 Answers

You can use the form attribute and place your form/input wherever you like.

form A string specifying the element with which the input is associated (that is, its form owner). This string's value, if present, must match the id of a element in the same document. If this attribute isn't specified, the element is associated with the nearest containing form, if any.

The form attribute lets you place an input anywhere in the document but have it included with a form elsewhere in the document.

Example:

<form action="/save" method="PATCH" id="patch"></form>
<form action="/delete" method="DELETE" id="delete"></form>

<table>
  <tbody>
    <tr>
      <td><input form="patch" name="row_id" value="1"></td>
      <td><input form="patch" name="five" value="5"></td>
      <td><input form="patch" name="three" value="3"></td>
      <td><input form="patch" type="submit" value="Save This Row"></td>
      <td>
        <input form="delete" name="row_id" value="1">
        <input form="delete" type="submit" value="Delete This Row">
      </td>
    </tr>
  </tbody>
</table>

you can also take advantage of the formaction and the formmethod attribute on the submit button for a more dynamic form

like image 161
Endless Avatar answered Oct 16 '22 22:10

Endless