I have the following code (pulled from this question) for setting a character limit on textareas.
function maxLength(el) {
if (!("maxLength" in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
var maxtext = document.getElementsByClassName("maxtext");
for (var i = 0; i < maxtext.length; i++) {
maxLength(maxtext[i]);
}
And an example of my html for textareas:
<textarea maxlength="150" class="maxtext"></textarea>
This all works just fine in Firefox and Chrome. In IE7+, it will stop me if I type up to the limit, but I'm then able to copy/paste text without restriction.
Any way to modify this script to prevent copy/pasting beyond the max character limit?
I have the following code (pulled from this question) for setting a character limit on textareas.
function maxLength(el) {
if (!("maxLength" in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
var maxtext = document.getElementsByClassName("maxtext");
for (var i = 0; i < maxtext.length; i++) {
maxLength(maxtext[i]);
}
And an example of my html for textareas:
<textarea maxlength="150" class="maxtext"></textarea>
This all works just fine in Firefox and Chrome. In IE7+, it will stop me if I type up to the limit, but I'm then able to copy/paste text without restriction.
Any way to modify this script to prevent copy/pasting beyond the max character limit?
Share Improve this question edited May 23, 2017 at 12:25 CommunityBot 11 silver badge asked Mar 22, 2013 at 15:02 Brian PhillipsBrian Phillips 4,4252 gold badges28 silver badges40 bronze badges 3 |2 Answers
Reset to default 15Listen for the onpaste
event. Once the event fires, grab the text from the clipboard and manipulate it how you like.
HTML
<textarea id="test" maxlength="10" class="maxtext"></textarea>
JAVASCRIPT
var test = document.getElementById("test");
test.onpaste = function(e){
//do some IE browser checking for e
var max = test.getAttribute("maxlength");
e.clipboardData.getData('text/plain').slice(0, max);
};
EXAMPLE
You could listen to the onchange
event to check the content length, if exceeds the limit then subtract it.
maxlength
is a HTML5 standard which is only supported from IE10+. – Nope Commented Mar 22, 2013 at 15:09byteLimit
jQuery plugion for example – Bergi Commented Mar 22, 2013 at 15:14