Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limit how many characters can be pasted in textarea

Is it possible to detect how many characters are being pasted into a HTML textarea, and cancel the paste if beyond a limit?

Edit: what I am trying to do is prevent the user pasting a massive amount of characters (~3 million) because it crashes some browsers. So I want to cancel the paste before their browser locks up. I am making a document editor where users are likely to try this. But they can type as much as they want.

like image 511
hoju Avatar asked Feb 03 '10 07:02

hoju


People also ask

How do I limit characters in a textarea?

The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element. Attribute Value: number: It contains single value number which allows the maximum number of character in Textarea element.

How do I limit characters in a textbox in HTML?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

What is the way to keep users from typing text into a large text area?

What is the way to keep users from typing text into a large text area? For input type="text" , we can use the size attribute to specify the visible size of the field, in characters. But we can also use the maxlength attribute to specify the maximum amount of characters that can be entered.


2 Answers

you can do this on jQuery like this:

$(document).ready(function(){
function limits(obj, limit){

    var text = $(obj).val(); 
    var length = text.length;
    if(length > limit){
       $(obj).val(text.substr(0,limit));
     } else { // alert the user of the remaining char. I do alert here, but you can do any other thing you like
      alert(limit -length+ " characters remaining!");
     }
 }


$('textarea').keyup(function(){

    limits($(this), 20);
})

  })

view a demo here.

like image 86
Reigel Avatar answered Sep 18 '22 16:09

Reigel


$("textarea").blur(function(event) {
    var maxLength = 3000000;
    var length = this.value.length;
    if (length > maxLength) {
        //reassign substring of max length to text area value
        this.value = this.value.substring(0, maxLength);
        alert(maxLength + ' characters allowed, excess characters trimmed');
    }
});

This jquery attaches the anonymous function to textareas, this will trim the text and alert the user, you can also attach it to the keypress event.

See: http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html for further details on that.

like image 31
StuperUser Avatar answered Sep 18 '22 16:09

StuperUser