【问题标题】:My JavaScript doesn't run when the html is in a form当 html 在表单中时,我的 JavaScript 不运行
【发布时间】:2021-03-14 00:53:41
【问题描述】:

HTML

我在这里有一些简单的 html 输入,我想把它放在一个 POST 表单中

    <form method="POST">
        {% csrf_token %}
        <input type="text" id="myTextInputID" placeholder="       Your amazon URL">
    </form>

JAVASCRIPT

function search(){
    var inputValue = document.getElementById("myTextInputID").value;
}


document.getElementById("myTextInputID").addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
      var input = document.getElementById("myTextInputID").value;
      document.getElementById(search());
      var error = document.getElementById("error")
      if (input.includes("https://www.amazon.co.uk/")){
        error.style.display = "none";
      }else{
        error.style.display = "block";
        setTimeout(function(){error.style.display = "none";} ,2000)
        
      }
    }
});
function togglePopup(){
  document.getElementById("popupe-1").classList.toggle("active");

}

当我没有将用户输入作为 post 方法时,我在这里有我的 if 函数,它工作得非常好,但是当我添加 post 方法时,页面每次都会重新加载并且不运行我的 javascript 函数

【问题讨论】:

  • 使用document.getElementById(search())是什么意思;在 eventListener 里面。
  • 表单有一个可以阻止的提交方法 - 你想阻止它吗?
  • 你是在暗示我不需要引用另一个函数
  • 为了回答第二个问题,我希望它在用户输入不符合条件时显示错误消息,如果满足则提交表单

标签: javascript html django web


【解决方案1】:

这是因为当用户按下回车时,它会触发表单提交动作,并且会重新加载页面。

为防止表单提交操作成为触发器,请将onkeydown="return event.key != 'Enter';" 添加到您的表单中。

function search(){
    var inputValue = document.getElementById("myTextInputID").value;
}


document.getElementById("myTextInputID").addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
      var input = document.getElementById("myTextInputID").value;
      document.getElementById(search());
      var error = document.getElementById("error")
      if (input.includes("https://www.amazon.co.uk/")){
        error.style.display = "none";
      }else{
        error.style.display = "block";
        setTimeout(function(){error.style.display = "none";} ,2000)
        
      }
    }
});
function togglePopup(){
  document.getElementById("popupe-1").classList.toggle("active");

}
<form action="https://www.google.com" method="POST" onkeydown="return event.key != 'Enter';">
  <input type="text" id="myTextInputID" value="https://www.amazon.co.uk/" />
</form>

<div id="popupe-1">Helloworld</div>
<div id="error">I'm a error</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 2016-07-02
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2012-05-21
    • 1970-01-01
    相关资源
    最近更新 更多