【问题标题】:Send form when enter is clicked inside textarea jquery在textarea jquery中单击输入时发送表单
【发布时间】:2021-09-26 03:38:27
【问题描述】:

我有这个 jquery

$(document).ready(function () {
         $("#submitmsg").click(function () {
           var clientmsg = $("#usermsg").val();
           $.post("post.php", { text: clientmsg });
           $("#usermsg").val("");
           return false;
         });
       });

这是我的html

<form name="message" action="" id="message">
 <textarea  name="usermsg" id="usermsg"></textarea>
 <div class="submit"><input name="submitmsg" type="submit" id="submitmsg" value="Send"></div>
</form>

此时只能通过按下按钮发送表单。但是,我想通过单击文本区域内的输入来发送它。但我还需要能够通过按 shift + enter 来换行。

我如何在 jquery 中做到这一点?我试过了:

     $("#usermsg").keypress(function (e) {
      if (e.which == 13) {
       var clientmsg = $("#usermsg").val();
        $.post("post.php", { text: clientmsg });
        $("#usermsg").val("");
        return false;
      }
    });

但我不能让它在换档时断线。

谢谢。

【问题讨论】:

    标签: jquery forms


    【解决方案1】:

    检查事件对象的shiftKey属性

    $("#usermsg").keypress(function(e) {
      if (e.which == 13) {  
        console.log(e.shiftKey ? 'Shift & Enter' : 'Enter only')
        if (!e.shiftKey) {
          // do ajax here
          return false
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form name="message" action="" id="message">
     <textarea  name="usermsg" id="usermsg"></textarea>
     <div class="submit"><input name="submitmsg" type="submit" id="submitmsg" value="Send"></div>
    </form>

    【讨论】:

    • 太好了,谢谢。顺便说一句,有没有办法将两个功能合并为一个?那么表单是通过按下按钮和回车来发送的?
    • 不要在按钮上使用点击事件,而是在表单上使用提交事件,然后在按键中执行$('#message').submit()
    猜你喜欢
    • 2015-02-11
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多