Bob Diego Bob Diego - 5 months ago 15
jQuery Question

jQuery ignore enter key until min length in textarea, then bind to submit

I'm looking to mimic the behavior of the Facebook comment box, using jQuery, where the field submits upon enter - but not until a minimum number of characters have been entered.

I have this version here:

$(function() {
$("textarea.commentfield").keypress(function (e) {

// fire on enter key
if ( (e.which == 13) && (this.value.length >= 3) ) {


This submits when 3 or more characters in the texarea - however, if the user hits enter before the minimum characters, it inserts a line return.

How can I prevent this behavior - essentially ignore the enter key until the minimum length is reached?

Answer

Event.preventDefault() will keep the key pressed from being displayed

$(function() {
  $("textarea").keypress(function(e) {
    if (e.which == 13) {
      if (this.value.length >= 3) {
        console.log('submitting');
      } else {
        e.preventDefault();
      }
    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>