HTML のフォームコントロール要素をフォーム外に置く2021年12月02日 21時47分

この記事は HTML アドベントカレンダーの 2 日目の分です。


HTML のフォームコントロール要素 (input 要素、textarea 要素、select 要素、button 要素など) は、基本的にはその要素の祖先に位置する (その要素を取り囲む) form 要素に紐づいています。しかし、実は祖先にない form 要素に紐づけることもできます。フォームコントロール要素の form 属性の値に、紐づけたい form 要素の ID (id 属性の値) を指定すればよいのです。

この機能を使えば、フォームの一部に別のフォームの送信ボタンを埋め込んだり、

<form id="edit-form" method="post" action="/edit">
  ...
  <p>
    <button type="submit">保存する</button>
    <button type="submit" form="delete-form">削除する</button>
  </p>
</form>
<form id="delete-form" method="post" action="/delete">
</form>

表の行ごとに異なるフォームを配置したりできます。

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>タイトル</th>
      <th>操作</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        1
        <form id="edit-form-1" method="post" action="/edit">
          <input type="hidden" name="id" value="1">
        </form>
      </td>
      <td>
        <input name="title" value="" form="edit-form-1">
      </td>
      <td>
        <button type="submit" form="edit-form-1">保存する</button>
      </td>
    </tr>
    <tr>
      <td>
        2
        <form id="edit-form-2" method="post" action="/edit">
          <input type="hidden" name="id" value="2">
        </form>
      </td>
      <td>
        <input name="title" value="" form="edit-form-2">
      </td>
      <td>
        <button type="submit" form="edit-form-2">保存する</button>
      </td>
    </tr>
    ...
  </tbody>
</table>

コメント

コメントをどうぞ

※メールアドレスとURLの入力は必須ではありません。 入力されたメールアドレスは記事に反映されず、ブログの管理者のみが参照できます。

※投稿には管理者が設定した質問に答える必要があります。

名前:
メールアドレス:
URL:
次の質問に答えてください:
「ハイパーテキストマークアップ言語」をアルファベット4文字でいうと?

コメント:

トラックバック

このエントリのトラックバックURL: http://nanto.asablo.jp/blog/2021/12/02/9445014/tb