表单提交重定向取决于用户输入



提前道歉-我对所有编码都很陌生,需要一些帮助。

这是我当前的HTML:

<!DOCTYPE html>
<html>
  <body>
    <form action="form_output.htm">
      Input:<br>
      <input type="text" name="input" value="Enter here">
      <br><br>
      <input type="submit" value="Submit">
    </form> 
    <p>Click 'Submit' to continue.</p>
  </body>
</html>

很简单。。。

但是,我需要它根据用户的输入将用户重定向到特定的页面。

例如,如果用户要输入cat,我希望目标页面是form_output_cat.htm

不确定单独使用HTML是否可行,但任何指导都将不胜感激:)

谢谢,

Ben

这个JavaScript能满足您的要求吗?

将其添加到底部的<script>标记中,就在</body>之前。

const input = document.querySelector("[name=input]");
const form = input.parentNode;
input.addEventListener("input", () => {
  form.action = `form_output_${input.value}`;
});

当用户更改input中的值时,可以更改action属性。

var form = document.querySelector('form');
document.querySelector('input').addEventListener('change', function() {
  form.setAttribute('action', 'form_output_' + this.value + '.html');
});
form.addEventListener('submit', function(event) {
  event.preventDefault();
  alert('form should send to: ' + form.getAttribute('action'));  
});
<!DOCTYPE html>
<html>
  <body>
    <form action="form_output.htm">
      Input:<br>
      <input type="text" name="input" placeholder="Enter here">
      <br><br>
      <input type="submit" value="Submit">
    </form> 
    <p>Click 'Submit' to continue.</p>
  </body>
</html>

相关内容

最新更新