DIV CSS 佈局教程網

用 JavaScript 動態切換表單 action 的兩種方法
編輯:關於JavaScript     

同一個搜尋框,使用者選了不同分類就該送到不同頁面——這時動態改寫表單的 action 是最直接的做法。以下示範兩種常見情境。

方法一:依下拉選單切換

為 select 掛上 onchange,取出選取值後決定要送去的位址:

<form id="form1" name="form1" method="post" action="../news/index.asp">
 <table width="100%" height="43" border="0" cellpadding="0" cellspacing="0">
 <tr>
  <td height="28">
   <input name="keyword" type="text" style="width:150px" id="keyword"/>
  </td>
 </tr>
 <tr>
  <td height="28">
   <select name="Searchtype" style="width:110px" id="Searchtype" onchange="Searchtype1();">
    <option value="news" selected="selected">新聞中心</option>
    <option value="case">工程案例</option>
   </select>
   <input type="submit" name="Submit" value="搜索" />
  </td>
 </tr>
 </table>
</form>

<script language="javascript">
function Searchtype1(){
  var type = document.getElementById("Searchtype")
             .options[document.getElementById("Searchtype").selectedIndex].value;

  if (type == "news") {
    document.getElementById("form1").action = "../news/index.asp";
  } else if (type == "case") {
    document.getElementById("form1").action = "../case/index.asp";
  }
}
</script>

方法二:依單選按鈕切換

在表單的 onSubmit 中判斷核取狀態,送出前才決定要導向哪一頁:

<html>
<head>
<script language="javascript">
function check(){
  if (document.form1.a[0].checked == true) {
    document.form1.action = "1.htm";
  } else {
    document.form1.action = "2.htm";
  }
}
</script>
</head>
<body>
<form name="form1" method="post" action="" onSubmit="check();">
 轉到頁面一<input type="radio" name="a">
 轉到頁面二<input type="radio" name="a">
 <input name="" type="submit" value="提交">
</form>
</body>
</html>

寫得更保險一些

兩個範例都可以再改良:取值時 document.getElementById('Searchtype').value 就等同那串 options 索引寫法,簡潔得多;另外若表單要送到不同後端,建議用隱藏欄位傳遞「類型」,讓伺服器端統一在一個端點處理,而不是靠前端切換 URL。若使用表單驗證,記得在 onSubmit 中於條件不成立時 return false,否則表單仍會送出。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved