【问题标题】:Shortcut to submit a form from textarea on keyboard operation通过键盘操作从 textarea 提交表单的快捷方式
【发布时间】:2018-07-21 01:50:03
【问题描述】:

我想通过以下代码提交带键盘的表单:

<form class="article-footnote-form footnote-form" style="margin-top:10px" >
<div class="form-group row">
    <div class="col-md-9">
        <textarea class="form-control" name="footnote" rows="3" autofocus></textarea>
    </div>
    <div class="col-md-3">
        <button class="btn btn-primary" type="submit" id="articleFootnoteBtn">Add Annotation</button>
    </div>
</div>
</form>

我使用.submit() 快捷方式提交并希望利用其隐式按键提交

 $(".article-footnote-form").submit(function(e){
    e.preventDefault();

很遗憾,它不起作用,我必须点击提交。

我在Enter to submit shift+enter to feedline找到了一个很好的解决方案

$("#textareaId").keypress(function (e) {
    if(e.which == 13 && !e.shiftKey) {        
        $(this).closest("form").submit();
        e.preventDefault();
        return false;
    }
});

但是,当更改触发事件时,我应该根据以前更新大量代码。

可以让 $("form").submit() 在 textarea 上工作,就像在 input type="text" 上工作一样?

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    您可以检查 keycode 是否为 13(输入键)并且该键不是 Shift 以提交表单。

    注意:您应该在提交表单之前阻止默认操作,而不是之后。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form class="article-footnote-form footnote-form" style="margin-top:10px" id="footnoteForm">
    <div class="form-group row">
        <div class="col-md-9">
            <textarea class="form-control" name="footnote" rows="3" autofocus></textarea>
        </div>
        <div class="col-md-3">
            <button class="btn btn-primary" type="submit" id="articleFootnoteBtn">Add Annotation</button>
        </div>
    </div>
    </form>
    <script>
    $("textarea").keypress(function(e){
      if(e.which==13 && !e.shiftKey){
        e.preventDefault();
        $('#footnoteForm').submit();
      }
    });
    $("#footnoteForm").submit(function(e){
      alert("Submitting form!");
    });
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 2017-05-13
      相关资源
      最近更新 更多