跳到主要内容

表单元素

form 元素承载什么?​

  • 作用: 定义表单, 把一组控件组织成一个数据提交单元;
  • 结构: form 内的控件随该表单一起提交;
<form action="/my-handling-form-page" method="post"></form>

action、method、enctype 分别控制什么?​

属性作用
action表单数据发送到的位置
method数据发送方法, get 或 post
enctype发送数据的 Content-Type 值, 即编码方式

label 元素如何与控件关联?​

  • 方式一: label 的 for 等于控件的 id;
  • 方式二: 把控件嵌套在 label 标签内部;
  • 效果: 点击说明文字即作用于关联控件, 辅助技术能读出控件名称;
  • 可访问性: label 是关键标签, 与表单控件推荐一一对应;
<label for="cheese">Do you like cheese?</label> <label>Click me <input type="text" /></label>

fieldset 与 legend 如何分组控件?​

  • fieldset: 把作用相同的一组控件包在一起;
  • legend: 嵌套在 fieldset 内, 声明这组控件的用途;
<form>
<fieldset>
<legend>Fruit juice size</legend>
<p>
<input type="radio" name="size" id="size_1" value="small" />
<label for="size_1">Small</label>
</p>
<p>
<input type="radio" name="size" id="size_2" value="medium" />
<label for="size_2">Medium</label>
</p>
</fieldset>
</form>

output 元素如何显示计算结果?​

  • 语义: 显示多个关联控件的计算结果, 或关联控件的当前值;
  • for: 空格分隔的关联控件 id 列表;
  • 更新: 配合 oninput 在控件值变化时重算;
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" id="b" name="b" value="50" /> +
<input type="number" id="a" name="a" value="10" /> =
<output name="result" for="a b">60</output>
</form>