How can I stop an user from typing more characters into a textarea when a maximum amount of characters is reached?
Im using ng-keypress right now but I can't figure out how to prevent the input when the limit is reached. The user should not be able to enter or paste more than 1000 characters in total into that textarea.
The question is about how to stop the input, not how to Count the Input lenght, this part is already working fine for me.
$scope.$watch('comment.Comment.body', function (newValue, oldValue) {
if (newValue) {
$scope.commentLength = 1000 - newValue.length;
}
});
// Tried this, nothing stops it
$scope.updateBody = function (event) {
event.cancel();
event.stop();
return false;
};
HTML
<textarea
ng-model="comment.Comment.body"
name="comment[Comment][body]"
placeholder="Your comment..."
ng-keypress="updateBody($event)">
</textarea>
<p>
{{commentLength}} remaining
</p>
Solution:
My mistake was I just had a typo somewhere but the given answer is not 100% OK. Instead of using the oldValue
it is required to substring()
the newValue
. If you don't do that you can't paste a text that goes over the 1000 characters into the text area. Using the newValue
allows you to paste and cut the text down to the Limit.
$scope.$watch('comment.Comment.body', function (newValue) {
if (newValue && newValue.length > 1000) {
$scope.comment.Comment.body = newValue.substring(0, 1000);
}
// Must be checked against undefined or you get problems when removing text
if (newValue != undefined) {
$scope.commentLength = 1000 - newValue.length;
}
});