Bob Diego
Bob Diego

Reputation: 575

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 Textarea - 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?

Upvotes: 2

Views: 187

Answers (2)

mujuonly
mujuonly

Reputation: 11861

As an alternative to Juan's answer, you can return false from an event handler to prevent its default behavior.

$(document).ready(function() {

  $("textarea.commentfield").keypress(function(e) {
    // fire on enter key
    if ((e.keyCode || e.which) == 13) {
      if (this.value.length >= 3) {
        $(this).parents('form').submit();
      } else {
        return false;
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="" class="commentfield"></textarea>

Note that return false only works in jQuery handlers, not in handlers using addEventListener. See http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/

Upvotes: 2

Ruan Mendes
Ruan Mendes

Reputation: 92284

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>

Upvotes: 1

Related Questions