Can input be limited to html – Paul D. Waite Sep 24 '12 at 16:12

  • @octopusgrabbus I deserved the downvote. I answered too fast, from my phone, and forgot about the support issue. Thanks for your edit and accept (feel free to accept a different answer if you wish, BTW). I just edited the answer further to make it more complete. – bfavaretto Sep 24 '12 at 16:35
  • 2

    HTML5 offers the maxLength attribute. Otherwise, you'd need some javascript, in jQuery, you'd do something like

    maxLength = 50;
    $("textarea").on("keydown paste", function(e){
      if ($(this).val().length>=maxLength) e.preventDefault();
    });
    
    standup75
    • 4,734
    • 6
    • 28
    • 49
    2

    you can use the maxlength="255" (it specifies the maximum number of characters allowed in the element.)

    or you can also do this by the jquery here i found the tutorial

    html

    <textarea cols="30" rows="5" maxlength="10"></textarea>
    

    jquery

    jQuery(function($) {
    
      // ignore these keys
      var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];
    
      // use keypress instead of keydown as that's the only
      // place keystrokes could be canceled in Opera
      var eventName = 'keypress';
    
      // handle textareas with maxlength attribute
      $('textarea[maxlength]')
    
        // this is where the magic happens
        .live(eventName, function(event) {
          var self = $(this),
              maxlength = self.attr('maxlength'),
              code = $.data(this, 'keycode');
    
          // check if maxlength has a value.
          // The value must be greater than 0
          if (maxlength && maxlength > 0) {
    
            // continue with this keystroke if maxlength
            // not reached or one of the ignored keys were pressed.
            return ( self.val().length < maxlength
                     || $.inArray(code, ignore) !== -1 );
    
          }
        })
    
        // store keyCode from keydown event for later use
        .live('keydown', function(event) {
          $.data(this, 'keycode', event.keyCode || event.which);
        });
    
    });
    

    Live example

    NullPoiиteя
    • 56,591
    • 22
    • 125
    • 143