正在加载...

HTML Select

上一课 textarea 收集自由多行文字。select 是另一件事:从固定列表选一个答案,而不是自由输入。

为什么需要 select

配送、餐食和设置需要封闭选项。随意输入会弄脏数据;从列表选 teh 不会。select 是控件;每个 option 是一项。select 上仍需要 label 与 name。

直接回答

1) 带 option 的 select。2) 关联 label。3) name 在 select;value 在 option。4) 可选空选项、selected、disabled、optgroup。5) 列表选择——不是上一课的 textarea 段落。

📊 Select pieces beginners use

Piece Role Beginner tip
select Choice container Owns name= for the submitted field key
option One choice value= is what posts; text is what users see
optgroup Section header Groups options; not itself submitted
name (on select) Submit key Required if the choice should post
id (on select) Label hook Match label for=
value (on option) Submitted token Prefer short stable codes (teh, salad)
selected Default pick At most one in a single-select list
disabled (option) Unavailable Shown but not choosable

配送:城市 select

配送备注用单行 input;城市用 select。先放空的 Choose。提交 teh/isf 等代码。

Labeled city select

html
<form action="/ship" method="post">
<label for="city">City</label>
<select id="city" name="city" required>
<option value="">Choose…</option>
<option value="teh">Tehran</option>
<option value="isf">Isfahan</option>
<option value="shir">Shiraz</option>
</select>

<label for="note">Delivery note</label>
<input id="note" name="note" type="text" placeholder="Gate code, floor…">

<button type="submit">Continue</button>
</form>

阅读城市示例

  • 列表控件是 select,不是 textarea
  • id 与 label for 配对
  • name 是提交键
  • 每个 option 有短 value
  • 空 value 避免误默认
  • required 直到选到真实城市
  • 备注是单行 input

用 optgroup 分组餐食

第二个示例含 Veg/Other。selected 作默认;disabled 表示售罄。

Meal select with optgroup

html
<label for="meal">Meal</label>
<select id="meal" name="meal">
<optgroup label="Veg">
<option value="salad">Salad</option>
<option value="soup" selected>Soup</option>
</optgroup>
<optgroup label="Other">
<option value="stew">Stew</option>
<option value="grill" disabled>Grill (sold out)</option>
</optgroup>
</select>

阅读餐食示例

  • optgroup 是分组标题,本身不提交
  • value 来自选中的 option
  • Soup 上有 selected
  • Grill 上有 disabled
  • 始终要 label 与 name
  • 下一课:可输入建议的 datalist

选择 select、textarea 还是 input

  • 已知列表:select
  • 自由段落:textarea
  • 短输入行:input
  • name 在 select;value 在 option
  • 始终要 label
  • 不要把列表写进 textarea

练习——搭建并分组

  1. 增加第四个城市短 value
  2. 改 Choose 文案;保持 value 为空
  3. 去掉再恢复 required
  4. 在分组间移动 Soup
  5. 试验 Grill 的 disabled
  6. 写一句:select 提交 value;textarea 提交自由文本
  7. 可输入建议留给下一课 datalist

易错点

  • 想要代码却漏了 value
  • 忘记 select 的 name
  • 没有 label
  • 把选项写进 textarea
  • 长列表没有 optgroup
  • 给每个 option 写 name
  • 与 datalist 混淆

小结

  • select + option = 从列表选择
  • select 上要 label 与 name
  • option 的 value 会提交
  • 可选 prompt、selected、disabled、optgroup
  • 不是自由多行文本
  • 下一课:datalist

🧠 测试您的知识

准备开始

测试您的知识

通过这个互动测验挑战自己,看看你对这个主题的理解程度如何

❓
5
问题
🎯
70%
及格要求
♾️
∞
时间
🔄
∞
尝试次数

📝 说明

  • 仔细阅读每个问题
  • 为每个问题选择最佳答案
  • 您可以随时重新参加测验
  • 您的进度将显示在顶部