3

How do I "lock" a textarea with jQuery so that no more characters can be entered? I don't want to necessarily disable it since I want to allow characters to be deleted.

update: oops..it just came to me: if I am limiting the length to say 400 characters then i can use the following when the length is > 400:

this.value = this.value.substring(0, 400);

which will just trim the excess

oym
  • 6,983
  • 16
  • 62
  • 88
  • 1
    Just a point about all the solutions below: none of them prevent mouse-based copy-paste into a textarea. – Joe Chung Aug 20 '09 at 04:49
  • 1
    Also, be sure that you validate the character count server-side. Client-side validation isn't safe. – sjstrutt Aug 20 '09 at 05:26

4 Answers4

3

following is quick contraption from modification of jquery.numeric plugin :)

It allows special keys but don't let user type anything.

<textarea id="txt" rows="5" cols="50"></textarea>

<script type="text/javascript">
$(document).ready(function(){
   $("#txt").keypress(function(e){
         var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
         // allow Ctrl+A
         if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) 
                                     /* opera */) return true;
         // allow Ctrl+X (cut)
         if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) 
                                     /* opera */) return true;
         // allow Ctrl+C (copy)
         if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) 
                                     /* opera */) return true;
         // allow Ctrl+Z (undo)
         if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) 
                                     /* opera */) return true;
         // allow or deny Ctrl+V (paste), Shift+Ins
         if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) 
                                     /* opera */
         || (e.shiftKey && key == 45)) return true;
         //page up, down, home end, left-right-up-down
         if(key > 32 && key < 40) return true;

         // if DEL or BACKSPACE is pressed
         return key == 46 || key == 8;

   });
});
</script>
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
  • Wouldn't it be better to get rid of those comments by using descriptive constants instead of key codes? `if (e.ctrlKey && key == keys[CTRL_A]) ...` – kangax Aug 20 '09 at 04:51
1

Try this:

$("textarea").keypress(function(){ 
  if($(this).val().length>=10) 
    return false; 
});

Demo here: http://jsbin.com/erama

Ariel Popovsky
  • 4,787
  • 2
  • 28
  • 30
0

You could bind to the keypress/keydown event of the textarea and block out all characters except backspace and delete. This way the user can delete characters but can't add/remove new characters.

You bind to the keypress event like this:

$('#text-area').keypress(function(e) {});

Then you can use the keyCode property of the event object (argument e) that is passed to check if the pressed key is delete or backspace. You can find more information on the keypress event on the jquery website.

You can base yourself on a list of keycodes to only allow delete and backspace. In this case keyCode should be equal to 8 or 46.

So the resulting code would be something like this (not tested though):

$('#text-area').keypress(function(e) { if(e.keyCode != 8 && e.keyCode != 46) { e.preventDefault(); } }); 

The preventDefault function of the event will stop any further processing, so if the characters is not delete or backspace it will not be typed.

Peter Eysermans
  • 479
  • 3
  • 13
  • 1
    You have to take care of other events also. User can also drop text and paste text. – rahul Aug 20 '09 at 04:34
  • this is much more sophisticated than my approach of just trimming off the excess once the max is reached...maybe this is overly complicated for what I need? – oym Aug 20 '09 at 04:36
  • As phoenix points out, this is not (yet) flawless and if you can achieve what you need with the code your solution, which is much lesser code, I would certainly go with that solution. @phoenix I would expect that pasting also is a keypress event (when using ctrl+v), I would need to test that out though? Although the different actions with the mouse should also be caught that's right. – Peter Eysermans Aug 20 '09 at 04:40
0

Here is plugin to limit input to textboxes/textareas

    jQuery.fn.charlimit = function(prompt, limit) {
        this.keyup(function(e) {
            var txt = $(this).val();
            var c = txt.length;

            if (prompt != null || prompt != 'undefined') {
                $(prompt).html((limit - c) + " chars left.");
            }
            if (c > limit) {
                $(this).val(txt.substring(0, limit));
                return false;
            }
            return true;
        });
        return this;
    }

prompt can be any span/div etc to show prompt message.

TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
  • That `prompt != null || prompt != 'undefined'` doesn't really guard from nonexistent element. Did you mean - `if (typeof prompt != 'undefined')`? – kangax Aug 20 '09 at 04:53