HTML input 的 form 属性
上一课用 required、placeholder 和范围细化字段行为。input 的 form 属性问的是另一件事:哪个表单拥有该控件,按钮能否临时覆盖 action?核心是表单外的 form="id"。提交按钮上的 form* 只改变该次点击的目标。
为何表单关联重要
多数字段嵌在 form 内。布局有时把控件放在别处。没有关联就不会进入 payload。form 通过表单 id 连接。嵌套仍是更清晰的默认;关联是困难布局的出路。
直接回答
1)给 form 设 id。2)外部控件写 form="同一-id"。3)仍需 name 与 label。4)提交按钮上可选 formaction、formmethod、formenctype、formnovalidate、formtarget,仅对该次点击。5)这是归属与提交路由——不是上一课的取值规则。
📊 Form association and submit overrides
| Attribute | Where | Beginner tip |
|---|---|---|
| form | input (or other control) | Value must match the form’s id exactly |
| formaction | submit button | Overrides form action for that click only |
| formmethod | submit button | Overrides method (get/post) for that click |
| formenctype | submit button | Overrides enctype when uploading via that button |
| formtarget | submit button | Overrides where the response opens (_blank, etc.) |
结账:表单外的字段
简短结账把邮箱和数量放在表单内。促销码稍后出现在标记中——带 label 与 name——并用 form="checkout" 加入。
<form id="checkout" action="/checkout" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label for="qty">Qty</label>
<input id="qty" name="qty" type="number" min="1" value="1">
<button type="submit">Pay</button>
</form>
<p>Promo field rendered later in the layout:</p>
<label for="promo">Promo code</label>
<input id="promo" name="promo" type="text" form="checkout"
placeholder="SAVE10">
阅读结账示例
- id=checkout 是挂钩
- form=checkout 让 promo 随提交
- name=promo 仍是载荷键
- 内部邮箱/数量不需要 form=
- 每个可见控件都要 label
- 可以有 required/min;重点是关联
双按钮:覆盖 action
有时一个表单两个目的地——草稿与发布。保留一个 form;每个按钮不同 formaction。仅该次点击覆盖。
<form id="article" action="/articles/publish" method="post">
<label for="title">Title</label>
<input id="title" name="title" type="text" required>
<label for="body">Body</label>
<input id="body" name="body" type="text">
<button type="submit">Publish</button>
<button type="submit" formaction="/articles/draft"
formmethod="post">Save draft</button>
</form>
阅读双按钮示例
- 默认路径用表单自身 action
- 草稿按钮经 formaction 发往别处
- formmethod=post 保持意图
- 两按钮提交相同命名字段
- form= 是归属;formaction 是按钮路由
- 下一课:多行 textarea
选择关联还是覆盖
- 树外字段:form="form-id"
- 相同字段、不同 URL:formaction
- 单次点击不同 method:formmethod
- 单次上传 enctype:formenctype
- 跳过校验(少用):formnovalidate
- 别处打开响应:formtarget
- 布局允许时优先嵌套
- 勿与 required/placeholder 混淆
练习——归属与覆盖
- 结账;去掉 promo 的 form= 再加回
- 写错 id——关联断裂
- 第二个外部 notes 字段带 form=checkout
- 对调草稿 formaction
- 短暂试用 formmethod=get
- 写一句:form= 选所有者;formaction 只改该按钮
- 把 promo 嵌回表单并去掉 form=
易错点
- id 与 form= 拼写不一致
- 有 form= 却忘了 name
- 过度使用分离字段
- 与上一课辅助属性混淆
- 把 form= 与 formaction 搞混
- 以为每个控件都要 form=
- 用 formnovalidate 代替修好字段
小结
- form="id" 关联表单外控件
- 需要匹配的 id;name 与 label 仍重要
- 按钮用 formaction/formmethod/form* 覆盖
- 能嵌套就嵌套;布局迫使时再关联
- 归属/路由 ≠ 上一课字段规则
- 下一课:textarea
🧠 测试您的知识
测试您的知识
通过这个互动测验挑战自己,看看你对这个主题的理解程度如何
📝 说明
- 仔细阅读每个问题
- 为每个问题选择最佳答案
- 您可以随时重新参加测验
- 您的进度将显示在顶部