Bob Diego Bob Diego - 8 months ago 36
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?


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

$(function() {
  $("textarea").keypress(function(e) {
    if (e.which == 13) {
      if (this.value.length >= 3) {
      } else {
<script src=""></script>