Problems:
If textarea length exceeds its limit, and we give the input in the middle of the text than it start the truncate character from the end. But i don't want that textarea behavior.
What I want is, I only want to allow textarea that takes only 4000 character. and if user try to enter extra character than it should not be allowed.
$(document).ready(function () {
var cursorPosition=0;
var enterKey_code=0;
var maxlength=4000;
var flag=0;
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
$('#MaxChar').text(maxlength);
function countChar(key_event){
var text_value = $('#Comments').val();
var cursorPosition = $('#Comments').prop("selectionStart");
var len=text_value.length;
if (len > maxlength) {
flag=1;
$('#Comments').val(text_value.substring(0, maxlength));
}
$('#CurrentChar').html($('#Comments').val().length);
}
$('#Comments').keyup(function (key_event) {
countChar(key_event);
if(flag==1)
{
var c=$('#Comments');
setCaretToPos(c[0], cursorPosition+1);
flag=0;
}
});
$('#Comments').keydown(function (key_event) {
cursorPosition = $('#Comments').prop("selectionStart");
countChar(key_event);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
<label id="CurrentChar">0</label> / <label id="MaxChar">0</label>
<br />
<textarea rows="20" cols="40" id="Comments"></textarea>
</div>
Try simple HTML solution with maxlength
maxlength
Declares an upper bound on the number of characters the user can input. Normally the UI ignores attempts by the user to type in additional characters beyond this limit.
<textarea maxlength="4000"></textarea>
There is an alternate with jQuery plugin jQuery Max Length
simply use this:-
<textarea maxlength='4000' rows="20" cols="40" id="Comments"></textarea>
it automatically stops when user types 4000 characters. That means though user type more than 4000 characters, they don't get insert into the text area.
If you further wants to prompt an warning message to user when the limit exceeds, just add the below simple JavaScript piece of code.
$(function() {
$("textarea[maxlength]").bind('input propertychange', function() {
var maxLength = $(this).attr('maxlength');
if ($(this).val().length >= maxLength) {
alert("Hello! I am an alert box!!");
$(this).val($(this).val().substring(0, maxLength));
}
})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With