HTML5 為 <input> 新增了大量 type 值,例如 email、tel、range、url、number、date 等。但不同瀏覽器支援程度不一,寫在頁面上到底是生效還是退化為純文字,最好實際測一次。下面的範例會把頁面上所有 input 的 type 值列出來,方便逐一比對。
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>html5 取得 input 內容</title>
</head>
<body>
<input type="email" />
<input type="tel" />
<input type="range" />
<input type="url" />
<input type="number" />
<input type="date" />
<input type="datetime" />
<ol id="debug"></ol>
<script>
var d = document.getElementById('debug');
[].forEach.call(document.querySelectorAll('input'), function (el) {
d.innerHTML += '<li>' + el.type + ' / ' + el.getAttribute('type') + '</li>';
});
</script>
</body>
</html>
關鍵在於同時印出 el.type 與 el.getAttribute('type')。前者是 DOM 解析後的實際結果:如果瀏覽器不認得 date,el.type 會回傳 "text";後者則是原始 HTML 上寫的字串。兩者不一致,就代表這個 type 值被降級處理了。
取值的寫法本身也很通用:無論是 el.value、el.valueAsNumber(number/date 適用)或 el.checked(checkbox/radio),都是同一套 DOM 介面,所以取值程式碼不必為每個 type 分別撰寫,這正是 HTML5 表單控制項的設計優勢。
補充一點:範例原本使用的 datetime 已被規格移除,取而代之的是 datetime-local,實作時建議改用後者。