document.forms 收錄頁面上所有的 <form>,取 length 就是表單數量。
<!DOCTYPE html> <html> <body> <h1>sharejs.com</h1> <form name="Form1"></form> <form name="Form2"></form> <form></form> <p>Number of forms: <script> document.write(document.forms.length); </script> </p> </body> </html>
執行結果:
Number of forms: 3
document.forms 同時支援索引與名稱兩種取法,這是它比 getElementById 方便的地方:
document.forms[0] // 第一張表單
document.forms["Form1"] // 用 name 取
document.forms.Form1 // 也可以用點號,但 name 含特殊字元時不行
document.getElementById("frm1") // 用 id 取,最明確
要留意的是,document.forms["Form1"] 比對的是name 屬性而不是 id。如果表單只有 id 沒有 name,這種取法會拿到 undefined。反過來說,兩者同名時行為一致,但混用容易搞混,建議 name 與 id 取相同的值。
有的,這個範例有一個值得指出的地方:頁面上有三個空的 <form>,其中兩個有 name、一個完全沒屬性。這在真實專案裡通常是程式碼味道——空的 form 元素沒有任何作用,只會讓 document.forms.length 的數字失去意義,也讓後端拿到無從辨識的提交。
如果目的是「用 JS 動態送出一個 POST 請求」,正確做法不是塞一個空 form 在 HTML 裡,而是在需要的時候才建立:
function postTo(url, data) {
var f = document.createElement("form");
f.method = "post";
f.action = url;
f.style.display = "none";
Object.keys(data).forEach(function (key) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = data[key];
f.appendChild(input);
});
document.body.appendChild(f);
f.submit();
}
這樣 document.forms 的數量就只在真正有表單的時候增加,除錯時也比較不會被誤導。
最後補一個順序上的提醒:腳本若放在 <head>,執行時 body 還沒解析完,document.forms.length 會是 0。請把腳本移到 body 尾端,或包進 DOMContentLoaded。