我一直在努力想要解决这个问题。 为什么在多行文本框asp控件中,我有140个字符的限制,但有时我可以输入141或142个字符,特别是使用回车键?
这是我的代码
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);
}
}
}
答案 0 :(得分:0)
请尝试以下代码:
function CheckSize(textBox, maxLength)
{
if (textBox.value.length > maxLength)
{
alert("Max characters allowed are " + maxLength);
textBox.value = textBox.value.substr(0, maxLength);
}
}
答案 1 :(得分:0)
我的猜测是,您是否遇到了许多现代浏览器中出现的相当常见的maxLength
错误(do a Google search about it)。这是您可以解决的一个示例问题,虽然没有为每种情况(即粘贴)硬化。
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);
上