当达到最大字符数时,如何阻止用户在textarea中键入更多字符?
我现在正在使用ng-keypress,但我无法弄清楚如何在达到限制时阻止输入.用户不应该在该textarea中输入或粘贴超过1000个字符.
问题是关于如何停止输入,而不是如何计算输入长度,这部分对我来说已经很好了.
$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;
};
Run Code Online (Sandbox Code Playgroud)
HTML
<textarea
ng-model="comment.Comment.body"
name="comment[Comment][body]"
placeholder="Your comment..."
ng-keypress="updateBody($event)">
</textarea>
<p>
{{commentLength}} remaining
</p>
Run Code Online (Sandbox Code Playgroud)
解:
我的错误是我只是在某个地方有一个错字,但给定的答案不是100%好.而不是使用oldValue
它是必需substring()
的newValue
.如果不这样做,则无法将超过1000个字符的文本粘贴到文本区域中.使用newValue
允许您将文本粘贴并剪切到限制.
$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;
}
});
Run Code Online (Sandbox Code Playgroud)
Ijo*_*chy 18
您应该尝试使用maxlength属性.代码就像是
<textarea
ng-model="comment.Comment.body"
name="comment[Comment][body]"
placeholder="Your comment..."
maxlength="1000">
</textarea>
<p>
{{1000 - comment.Comment.body.length}} remaining
</p>
Run Code Online (Sandbox Code Playgroud)
Ras*_*lom 14
您可以使用角度输入功能中的"ng-maxlength",并在值无效时观察. https://docs.angularjs.org/api/ng/directive/input,但它不会阻止输入的可能性.
你也可以设置一个值的手表:
$scope.$watch('value', function(newVal, oldVal) {
if(newVal.length > 10) {
$scope.value = oldVal;
}
});
Run Code Online (Sandbox Code Playgroud)
指令方式:
app.directive('myBlock', function ($parse) {
return {
scope: {
validLength: '='
},
link: function (scope, elm, attrs) {
elm.bind('keypress', function(e){
// stop typing if length is equal or greater then limit
if(elm[0].value.length >= scope.validLength){
e.preventDefault();
return false;
}
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
演示 plunker
小智 5
<input type="text" name="usrname" maxlength="10">
Run Code Online (Sandbox Code Playgroud)
在您的 HTML 中使用 maxlength 。这是简单而有效的
归档时间: |
|
查看次数: |
49488 次 |
最近记录: |