【问题标题】:Catch HTML Form "Enter" Press to execute AJAX, not Post捕获 HTML 表单“Enter”按执行 AJAX,而不是 Post
【发布时间】:2021-09-02 06:33:49
【问题描述】:

我目前正在处理一个 HTML 表单(使用 pug 视图引擎构建它),我尝试在填写后在 ajax 请求中使用它。

在编辑我的输入元素后按 Enter 时,它似乎提交了表单(我想是发布请求?)。我想让 enter-press 事件(就像我的按钮一样)触发一个 jquery 函数。

表单构建如下:

form(class="form" action="")
  div(class="form-group")
    label(for="testid") Tickersymbol
    input(name="symbol", type="text", class="form-control", id="testid", placeholder="Please enter the symbol")
   div(class = "form-group")
     button(class="btn btn-primary" id="getdata" type="button") Get Info

当前的 JQuery 代码:

// This does not work
$("#inputStocksymbol").trigger('click', function (){
    console.log("Enter event should have happened.")
})

// This does work
$("#getquote").click( function () {
    console.log("Button has been pressed")
})

对于如何实现这一点有什么建议吗?

谢谢!

【问题讨论】:

    标签: javascript html jquery pug


    【解决方案1】:

    默认情况下,form 或 input 中的 Return 键将提交该表单。因此,如果您想在发生这种情况时运行一些逻辑,请与 submit 事件挂钩:

    $("form.form").on('submit', function(e) {
      e.preventDefault()
    
      // run your code here
    
      console.log("Button has been pressed");
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form class="form" action="">
      <div class="form-group">
        <label for="testid">Tickersymbol</label>
        <input name="symbol" type="text" class="form-control" id="testid" placeholder="Please enter the symbol" />
        <div class="form-group">
          <button class="btn btn-primary" id="getdata" type="button">Get data</button>
        </div>
      </div>
    </form>

    或者,如果您只想在输入中按下 Return 时运行一些代码,但不允许按键提交表单,您可以直接挂钩 keypress 事件处理程序输入,确保调用stopPropagation():

    $("#testid").on('keypress', e => {
      if (e.keyCode === 13) {
        e.preventDefault();
        e.stopPropagation();
        
        // run your code here
        
        console.log("Return has been pressed");
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form class="form" action="">
      <div class="form-group">
        <label for="testid">Tickersymbol</label>
        <input name="symbol" type="text" class="form-control" id="testid" placeholder="Please enter the symbol" />
        <div class="form-group">
          <button class="btn btn-primary" id="getdata" type="button">Get data</button>
        </div>
      </div>
    </form>

    【讨论】:

    • 非常感谢您的快速回答!还没有达到 preventDefault() 的想法。你拯救了这一天。干杯! (只要 Stackoverflow 允许,就会接受正确的;))
    猜你喜欢
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2012-01-07
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多