本文分享一個以 JS 控制表單提交的方法,可在提交前動態修改表單的 action,供大家參考。
<Script Language="JavaScript">
function autoSubmit() {
var form = document.forms[0];
var actionPath = "?mo=phone";
form.action = actionPath;
form.submit();
return true;
}
</Script>如果需要兩個提交按鈕,可讓其中一個的 type 為 "submit"(由按鈕本身提交),另一個為 "button"(由 JS 控制提交):
<form method="post" name="form1" id="form1" action="?mo=phone&do=opreat"> <input type="hidden" value="" name="phoneid" id="phoneid"> <table border="0px" style="font-size:12px" width="630px"> <tr> <td align="right">手機型號:</td> <td><input type="text" id="phonetype" name="phonetype" style="width:120px" /></td> </tr> <tr> <td align="right">類型:</td> <td><select name="type" id="type"><option value="1">手機</option></select></td> </tr> </table> <input type="submit" value="增加手機"> <input type="button" onclick="autoSubmit();" value="搜索手機"> </form>
透過 autoSubmit 函式,可在送出前先改寫 form.action,再呼叫 form.submit() 提交,實現以 JS 靈活控制提交目標的效果。