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.
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.
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? 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.
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.
$("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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With