首页 > 解决方案 > 在textarea jquery中单击输入时发送表单

问题描述

我有这个 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;
      }
    });

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

谢谢你。

标签: jqueryforms

解决方案


检查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>


推荐阅读