form.submit()在EventListener函数中不起作用

如果.value不相等,我将如何通过表单提交。香港专业教育学院尝试form.submit(),它什么也不做。但是当您将其设为我不需要的window.location时,它确实可以工作。

var slim = document.getElementById("1");
    var shady = document.getElementById("2");
    var standup = document.getElementById("3");
    var form = document.getElementById("form");
    form.addEventListener("submit", function(e) {
      e.preventDefault();
      if (
        standup.value === "stand up" &&
        shady.value === "shady" &&
        slim.value === "slim"
      ) {
        window.location = "https://example.com";
      } else {
        form.submit();
      }
    });

其他:提交此表格

<form id="form" action="/eyerepeat" method="get">
        <label for="fname">First name:</label>
        <input type="text" id="1" name="willthereal" /><br /><br />
        <label for="lname">Last name:</label>
        <input type="text" id="2" name="9" /><br /><br />
        <label for="action">Action:</label>
        <input type="text" id="3" name="please" /><br /><br />
        <input id="submit" type="submit" value="Submit" />
      </form>
评论
不要离开我
不要离开我

THe e.preventDefault() prevents the form from being submitted regardless, even if triggered programatically.

Instead, conditionally call e.preventDefault - only call if once you've determined that you don't want to submit it:

var slim = document.getElementById("1");
var shady = document.getElementById("2");
var standup = document.getElementById("3");
var form = document.getElementById("form");
form.addEventListener("submit", function(e) {  
  if (
    standup.value === "stand up" &&
    shady.value === "shady" &&
    slim.value === "slim"
  ) {
    e.preventDefault();
    window.location = "https://example.com";
  }
});
<form id="form" action="/eyerepeat" method="get">
  <label for="fname">First name:</label>
  <input type="text" id="1" name="willthereal" /><br /><br />
  <label for="lname">Last name:</label>
  <input type="text" id="2" name="9" /><br /><br />
  <label for="action">Action:</label>
  <input type="text" id="3" name="please" /><br /><br />
  <input id="submit" type="submit" value="Submit" />
</form>
点赞
评论