Skip to content Skip to sidebar Skip to footer

Check Size Of Multi-line Textbox

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

Solution 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

Solution 2:

Please try the following code:

functionCheckSize(textBox, maxLength)
{
    if (textBox.value.length > maxLength)
    {
        alert("Max characters allowed are " + maxLength);
        textBox.value = textBox.value.substr(0, maxLength);
    }
}

Post a Comment for "Check Size Of Multi-line Textbox"