每個 form 元素都有 form 屬性(HTMLFormElement 上的 form 回指所屬表單),所以「這個按鈕屬於哪個表單」只要兩步:取得按鈕,讀它的 form.id。
<form id="form1">
<button id="button1" type="button">Click me!</button>
</form>
<p>按鈕所屬表單的 id 是:
<script>
document.write(document.getElementById('button1').form.id);
</script>
</p>
上面這段會輸出 form1,也就是按鈕所屬表單的 id,而不是按鈕自己的 id。這一點值得特別強調,因為不少流傳的範例把結果寫成 button1,那是把 .form 這一段漏掉的緣故。
取得表單物件本身,而不只是 id。拿到物件之後就能直接操作表單:
const form = document.getElementById('button1').form;
form.action; // 提交網址
form.method; // 提交方法
form.reset(); // 重設表單
表單可以在 form 標籤外面。HTML5 允許用 form 屬性把控制項關聯到任意表單,這時 DOM 上的 .form 依然正確:
<form id="realForm"></form>
<button id="outsideBtn" form="realForm">送出</button>
<script>
console.log(document.getElementById('outsideBtn').form.id); // "realForm"
</script>
沒有所屬表單時回傳 null。如果按鈕不在任何表單內,也沒有 form 屬性,.form 會是 null,直接取 .id 就會拋錯。實務上請先判斷:
const btn = document.getElementById('button1');
const formId = btn.form ? btn.form.id : null;
不要用 document.write 輸出。它在文件載入完成後被呼叫會清空整個頁面。要顯示結果請操作既有元素:
document.getElementById('result').textContent = formId;
另外提醒一個常見誤會:button 若沒有指定 type,預設是 submit,點擊會直接送出表單。範例中寫 type="button" 是刻意的,避免測試時頁面被跳轉掉。
最後,id 只是最淺的一層資訊。真正實用時,通常你會需要整個表單物件來做序列化或欄位驗證;此時可以直接用 new FormData(form) 一次取得所有欄位,比逐一 getElementById 方便得多。