views:

1328

answers:

4

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

A: 

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.

PeterEysermans
You have to take care of other events also. User can also drop text and paste text.
rahul
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?
es11
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.@phoenixI 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.
PeterEysermans
+1  A: 

Try this:

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

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

Ariel Popovsky
+2  A: 

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
kangax
A: 

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
That `prompt != null || prompt != 'undefined'` doesn't really guard from nonexistent element. Did you mean - `if (typeof prompt != 'undefined')`?
kangax