要讀懂表單,得先釐清 input 標籤幾個關鍵屬性的含義:type、id、name 與 value。
type 決定瀏覽器中呈現的輸入控制項形式,例如 type="text" 是文字框,type="button" 是按鈕。可選值包括:
id 是唯一識別碼,不允許重複(類似資料表的主鍵),可透過它取得對應的HTML標籤物件。若同一頁面出現重複的 id,會導致難以預料的錯誤。
// 依指定的 id 取得物件引用
document.getElementById("id_value")
name 與 id 功能相似,同樣用來標識HTML標籤,唯一的不同是 name 允許有重複的值。
// 依指定的 name 取得物件引用陣列
document.forms[0].name
document.getElementsByName("name")
value 代表某個HTML標籤的值。舉例來說:
<input type="text" name="seq" value="hello!" id="seq007" />
你會看到網頁中的文字框內容為「hello!」。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form>
<input type="text" name="seq" value="" id="seq001" />
<input type="text" name="seq" value="" id="seq002" />
<input type="text" name="seq" value="" id="seq003" />
</form>
</body>
</html>
對應的JavaScript取值方式:
document.getElementById("seq001"):取得 id 為 seq001 的單一物件引用。document.forms[0].seq:回傳第一個表單中所有 name=seq 的標籤物件引用陣列。document.getElementsByName("seq"):回傳網頁中所有 name=seq 的標籤物件引用陣列。