I've been trying for hours to figure this out.
Why in a multi-line textbox asp control, I have a limit of 140 characters but sometimes I can input 141 or 142 characters, especially with the use of the enter key?
Here's my code
function CheckSize(o, size) {
if (o != null) {
var s = o.value.length;
if (s > size) {
debugger;
alert('Lamentamos mas foi atingido o limite máximo para o texto a introduzir.\nSugerimos que introduza um texto com menos de ' + size + ' caracteres.\nAgradecemos a sua compreensão.');
// alert(resources.error_reachedMaxNumberOfChars.replace("{0}",String(size)));
var trim = o.value.trim();
o.value = trim.substring(0, size - 1);
}
}
}
My guess is, is that you are running into the fairly common maxLength
bug that has been present in a number of modern browsers (do a Google search about it).This is an example of how you could work around the problem, though not hardened for every situation (i.e. paste).
CSS
.hidden {
visibility: hidden;
}
HTML
<textarea id="myTextbox" maxlength="140" rows="4" cols="35"></textarea>
<div id="count">0</div>
<div id="alert" class="hidden">At max chars!</div>
<div id="newline" class="hidden">Newline prevented as it is 2 characters!</div>
Javascript
var myTextBox = document.getElementById('myTextbox'),
count = document.getElementById('count'),
alert = document.getElementById('alert'),
newline = document.getElementById('newline'),
maxLength = 140;
myTextBox.addEventListener('input', function (e) {
var value = e.target.value.replace(/\r?\n/g, '\r\n'),
length = value.length;
if (length >= maxLength) {
if (length > maxLength) {
length = maxLength - 1;
e.target.value = value.slice(0, length);
newline.classList.remove('hidden');
} else {
alert.classList.remove('hidden');
newline.classList.add('hidden');
}
} else {
alert.classList.add('hidden');
newline.classList.add('hidden');
}
count.textContent = length;
}, false);
On jsFiddle
Please try the following code:
function CheckSize(textBox, maxLength)
{
if (textBox.value.length > maxLength)
{
alert("Max characters allowed are " + maxLength);
textBox.value = textBox.value.substr(0, maxLength);
}
}