表單的 action 屬性決定了資料要提交到哪個網址。有時候我們會希望表單提交回當前頁面,這時就可能把 action 設為空。若要透過 JavaScript 讀取這個屬性,只要取得表單物件後存取它的 action 即可。
下面的範例表單 action 設為 jb51.php,並用腳本輸出該值:
<!DOCTYPE html>
<html>
<body>
<form id="frm1" action="jb51.php">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
<input type="submit" value="Submit">
</form>
<p>The value of the action attribute is:
<script>
document.write(document.getElementById("frm1").action);
</script>
</p>
</body>
</html>
執行結果如下:
The value of the action attribute is: jb51.php
如此一來,就能在送出表單前動態檢查或修改提交目標,讓表單流程更具彈性。