Textarea not submitting on enter

2019-08-26 19:45发布

I know that this question is probably redundant, but after having looked through almost every related question on stackoverflow, I still haven't been able to make my problem "go away." The problem is this:

On key press of "enter", submit textarea contents instead of creating a new line.

This is what I am working with:
The jQuery (an answer from a similar question on here):

  $('#message').keypress(function(e){
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13){
      $('#form').submit();
    }
  });

The HTML:

<div class="message">
<form name="form" class="form" id="form" action="chatsendmesg.php" method="POST">
<textarea rows="2" name="message" id="message" class="message" placeholder="RM911 Chat" cols="26"></textarea>
<input id="submit" class="submit" type="submit" value="Send" name="submit">
</form>

Even with this code, the key press of "enter" still creates a new line instead of the submit. What on earth am I not understanding here?? Is it a lack of a preventDefault?

Thanks in advance, Tim

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-26 20:12

preventDefault will not work because for a textarea, the default action is to put the character (represented by the key stroke) in the text area. That is, none of your keystrokes will make it into the text area.

To prevent only the new line from being entered into the text area, you need to stop propagation of the keypress event, but only when the key pressed is ENTER, like this:

$("#void").keypress(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13){
      $('#form').submit();
      return false;  // stop propagation of the keypress
    }
   return true;
});
查看更多
叛逆
3楼-- · 2019-08-26 20:21

This works...

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script>
        $(function(){
             $("#message").keypress(function(e){
                var code = (e.keyCode ? e.keyCode : e.which);
                if (code == 13){
                      $("#form1").submit();   
                }
              });
        });
    </script>
  </head>
  <body>
    <div id="message">
      <form name="form1" class="form1" id="form1" action="chatsendmesg.php" method="post">
          <textarea rows="2" name="message" id="message" class="message" placeholder="RM911 Chat" cols="26"></textarea> 
          <input id="submit1" class="submit1" type="submit" value="Send" name="submit1" />
      </form>
    </div>
  </body>
</html>
查看更多
登录 后发表回答