Search code examples
htmlcsstextareapreventdefaultenter

event.PreventDefault() does not work when enter key is pressed on a textarea


My code is as follows. I have a textarea defined by class ".mytext", and i want to prevent the user from going to a new line upon clicking "enter". But even after following event.preventDeafult(), enter still takes the user to the next line in the textarea. Am i missing anything here?

$(document).off("keyup", ".mytext");
$(document).on("keyup", ".mytext", function(event) {
  if (event.which == 13) {
    event.preventDefault();
    $(this).siblings("#send_msg").trigger("click");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="mytext"></textarea>


Solution

  • By the time you've got to keyup it's too late, the newline is there.

    Insert another listener this time for keypress and prevent default at that point - and of course do whatever you want to do about simulating a click at the same time which means the newline won't be in the text string at that point.

    $(document).off("keyup", ".mytext");
    $(document).on("keypress", ".mytext", function(event) {
      if (event.which == 13) {
        event.preventDefault();
        $(this).siblings("#send_msg").trigger("click");
      }
    });
    $(document).on("keyup", ".mytext", function(event) {
    //this should now be redundant
      if (event.which == 13) {
        event.preventDefault();
        $(this).siblings("#send_msg").trigger("click");
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea class="mytext"></textarea>