Search code examples
javascriptjquerycharacter-limit

Javascript check text limit on submit


I have this JQuery code to limit text in a textarea to 250 characters:

    $('#postform textarea').keypress(function() {
         if($(this).val().length >= 250) {
            $(this).val($(this).val().slice(0, 250));
            return false;
        }
    });

Is it possible to change this code so users can type past the limit in the textarea, then when the user clicks the submit button it shows an alert if it is over the limit.

Any help appreciated.


Solution

  • Instead of keypress event use sumbit event on your form :

    $('#form').submit(function(event) {
        var $textarea = $(this).find('textarea')
        if($textarea.val().length >= 250) {
            // do what you want
            // show an error or
            // E.g : highlight the textarea in red
            $textarea.addClass('input-error');
            return false;
        }
        else {
            $textarea.removeClass('input-error');
        }
    });
    .input-error {
      border-color:red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="form" action="" method="form">
      <textarea></textarea>
      <button type="submit">Submit</button>
      </form>