我如何使用图像链接提交表单,以改变与JS(没有JQuery)的表单动作


How do I submit a form using image links to change form action with JS (no JQuery)?

我有一个搜索表单,需要处理3种不同的方式:

1)表单的默认动作应该使用return/enter键提交。

2)如果点击"image1",则需要更新$which_action变量并提交表单。

3)如果点击"image2",则需要更新$which_action变量并提交表单。

(我知道$which_action在客户端浏览器中不存在,我只是将其作为占位符包含在下面的代码中)

这是我目前想做的一些笔记:

<form method="POST" action="<?php echo $which_action ?>" id="query"> 
    <input type="text" value="<?php echo $_POST['query']; ?>" />
</form>
<image1>clicking this image should change $which_action=image1.php and POST the form value into $_POST['query'] while submitting the form.
<image2>clicking this image should change $which_action=image2.php and POST the form value into $_POST['query'] while submitting the form.

javascript不应该影响使用enter/return键提交表单的默认方法。

提前感谢!

  <form method="POST" action="" id="query"> 
<input type="text" value="<?php echo $_POST['query']; ?>" />
</form>
 <img src="" onclick="changeAction('image1.php')">
 <img src="" onclick="changeAction('image2.php')">
 <script>
   function changeAction(url) {
   document.getElementById("query").action = url;
   document.getElementById("query").submit();
  }
 </script>

你的意思是这样吗?http://jsfiddle.net/sebastianteres/mLBxR/

<form method="POST" action="<?php echo $which_action ?>" id="query"> 
  <input id="the_input" type="text" value="<?php echo $_POST['query']; ?>" />
</form>
<image1 onclick="changeValue("foo")>
<image2 onclick="changeValue("bar")>
<script>
  window.changeValue = function (val) {
     document.getElementById("the_input").value = val;   
  }
</script>

在该函数中,您可以搜索表单(带有id)并更改action属性。