在 Table 裡面使用 Form

有 N 人看过


把 form 放在 table, tbody, 或 tr 底下,瀏覽器會把 form 移動位子,而裡面的元素則會留在原位。

<!-- 原來應該是這樣子 -->
<form>
    ... input fields ...
</form>
<!-- 現在變成這樣子 -->
<form></form>
... inputs fields ...

如果將整個 table 封裝在 form 中,問題在於所有表單元素都將在 submit 時發送。此方法允許您為每個 row (tr) 定義一個表單,並在 submit 時僅發送該行資料。

將 form 包著 tr 周圍(或將 tr 包著 form)的問題在於它是無效的 html,因為 DOM 已損壞。

解法1 - HTML form attribute

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefform

<form method="GET" id="my_form"></form>

<table>
    <tr>
        <td>
            <input type="text" name="company" form="my_form" />
            <button type="button" form="my_form">ok</button>
        </td>
    </tr>
</table>

把 form fields 跟 form 標籤分離,利用 form tag 的 id 讓 form field 去做關聯。 (IE不支援)

解法2 - 做個假 table

<style>
  DIV.table {
      display:table;
  }
  FORM.tr, DIV.tr{
      display:table-row;
  }
  SPAN.td{
      display:table-cell;
  }
</style>

...

<div class="table">
  <form class="tr" method="post" action="blah.html">
    <span class="td"><input type="text"/></span>
    <span class="td"><input type="text"/></span>
  </form>
  <div class="tr">
    <span class="td">(cell data)</span>
    <span class="td">(cell data)</span>
  </div>
  ...
</div>

IE 7 不支援 CSS table, IE8 需要宣告 doctype 才可以使用。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Reference:
Form inside a table

本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。