I would like to limit the user to entering 10 characters into a text area, and to notify the user when they approach the limit. I'm doing this by setting the maxLength
attribute of the text area, and using some javascript to update a label as characters are entered.
But my javascript doesn't properly count new lines. Or at least it doesn't count them in the same manner as the textarea
element. If I enter the below sample input, my javascript will compute that 6 characters are being used and output that 4 characters are remaining, but the textarea
will not allow any more input.
Sample input: enter 'D', press return 4 times, enter 'D':
D
D
(I'm actually allowing more than 10, but a low number better exemplifies the issues)
function limitText() {
var textarea = document.getElementById('textarea');
var char_label = document.getElementById('charcount_text');
var count = textarea.value.length;
var max = textarea.maxLength;
console.log(count + " " + max);
var remaining = max - count;
if (remaining <= 0) {
char_label.innerHTML = '10 character limit reached.';
} else if (remaining <= 5) {
char_label.innerHTML = '10 character limit, ' + remaining + ' remaining.';
} else {
char_label.innerHTML = '';
}
}
textarea {
width:200px;
height:80px;
}
<textarea id="textarea" onKeyDown="limitText()" onKeyUp="limitText()" maxlength="10"></textarea>
<span class="charcount_text" name="charcount_text" id="charcount_text"></span>