<input> 是表單收集用戶資料的核心元素,透過 type 屬性切換多種輸入介面。本文為初學者整理基本類型、常用屬性、HTML5 驗證與無障礙基礎。
<form action="/submit" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
<button type="submit">送出</button>
</form>
type 決定輸入介面 (預設 text)。name 為表單提交的鍵名,**必須設定** 才會送出資料。id 搭配 <label for> 擴大點擊區域並提供無障礙支援。| type | 外觀/功能 | 常用屬性 |
|---|---|---|
text | 單行文字框 | placeholder, maxlength, pattern |
password | 遮罩顯示 (●●●) | autocomplete="current-password" |
email | 信箱格式驗證 + 專用鍵盤 | multiple 允許多信箱 |
tel | 電話號碼 (無格式強制) | pattern 自訂格式 |
number | 數值 + 微調鈕 | min, max, step |
date | 日期選擇器 (瀏覽器 UI) | min, max |
checkbox | 核取方塊 (布林) | checked, value |
radio | 單選按鈕 (同 name 分組) | checked, value |
file | 檔案選擇 | accept, multiple, capture |
submit | 提交按鈕 | value 按鈕文字 |
button | 一般按鈕 (需 JS) | — |
hidden | 隱藏欄位 | 傳遞 token/狀態 |
required:必填。pattern="regex":自訂正則驗證 (如 pattern="[0-9]{4}" 四位數字)。min, max, step:數值/日期範圍。type="email|url|tel":格式自動驗證。:invalid, :valid, :user-invalid (Firefox)。<label for="id"> 或 <label><input></label>。aria-describedby="error-id" 連結 <div id="error-id" role="alert">。tabindex、role、鍵盤事件。<input type="text"> (空元素無結束標籤)。<input type="text" /> (自閉合斜線)。name → 表單不送出該欄位資料。placeholder 替代 <label> → 無障礙缺失、密碼管理器無法辨識。type="number" 輸入非數值時 valueAsNumber 回傳 NaN,需注意。<input type="submit"> 放在 <form> 外部 → 需加 form="form-id" 關聯。熟練這些基礎,即可建構功能完整、無障礙友善的表單。