表單除了 id 之外通常也會有 name,後端在處理表單資料時常靠它來辨識。讀取方式同樣直接:form 物件的 name 屬性。
<!DOCTYPE html>
<html>
<body>
<form id="frm1" name="form1">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
</form>
<p>The name of the form is:
<script>
document.write(document.getElementById("frm1").name);
</script>
</p>
</body>
</html>
執行結果:
The name of the form is:form1
實務上建議兩者都設,而且值保持一致。原因是:getElementById() 只認 id,而 HTML 原生集合(如 document.forms、form.elements)以及部分舊式程式碼是用 name 來索引的。兩邊都給,取值時就有彈性。
幾種等價的寫法:
document.getElementById("frm1").name
document.forms["frm1"].name
document.forms[0].name
要注意的是,表單內的 input 若命名成 name,會與表單自身的 name 屬性產生衝突(DOM 會優先回傳那個 input 元素而不是字串)。這類命名污染問題在欄位名稱選擇上要避開,例如別把 input 取名為 action、method、submit、length 這些跟 form 內建屬性同名的字。