Textarea根据需要计算字符不起作用

时间:2016-03-02 14:47:58

标签: javascript

我有简单的脚本字符计数器,但我无法理解为什么它显示它是5或任何其他小于10的数字,作为剩余的字符。它必须显示它是“0”字符剩余并且它不计算如果我粘贴一些文字进入文本区域。我该如何解决这个问题?

HTML CODE

ZipFile

JS CODE

<textarea name="" id="txtarea" cols="30" rows="10"></textarea>
<p id="demo"></p>

4 个答案:

答案 0 :(得分:1)

问题在于:angular.module('starter') .controller('LoginCtrl', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) { $scope.loginForm = {} $scope.loginError = false; $scope.loginErrorText; $scope.login = function() { var credentials = { email: $scope.loginForm.email, password: $scope.loginForm.password } console.log(credentials); $auth.login(credentials).then(function() { console.log('im in login function' ); // Return an $http request for the authenticated user $http.get('http://localhost:8000/api/v1/auth/user').success(function(response){ // Stringify the retured data var user = JSON.stringify(response.user); // Set the stringified user data into local storage localStorage.setItem('user', user); // Getting current user data from local storage $rootScope.currentUser = response.user; // $rootScope.currentUser = localStorage.setItem('user');; $ionicHistory.nextViewOptions({ disableBack: true }); $state.go('app.jokes'); }) .error(function(){ $scope.loginError = true; $scope.loginErrorText = error.data.error; console.log($scope.loginErrorText); }) }); } });

应该是:if(txt.value.length < maxLength)

无论如何,我不会在keyDown事件中以时间间隔进行此操作。像这样:

&#13;
&#13;
if(txt.value.length <= maxLength)
&#13;
var txt = document.getElementById("txtarea");
txt.setAttribute("maxlength", 50)
var maxLength = 50;
var demo = document.getElementById("demo");
var checkLength = function(){
    if(txt.value.length <= maxLength) {
        var result = demo.innerHTML =  " Character remaining: " + (maxLength-txt.value.length) 
    };  
};
&#13;
&#13;
&#13;

答案 1 :(得分:1)

一,正如@jolmos所说,你必须检查它是否更少或等于。您只是检查它是否小于,因此它永远不会显示为“0”作为剩余字符数。

二,关于不能计算粘贴尝试将此checkLength()函数绑定到keyup / keydown事件而不是从间隔调用它时。

试试这个:

txt.addEventListener("keyup", function() {
if(txt.value.length <= maxLength) {
    var result = demo.innerHTML =  " Character remaining: " + (maxLength-txt.value.length) 
};
}

答案 2 :(得分:1)

如果您输入快速,它将永远不会显示4或5个字符。更好的解决方案是在其上放置onchange事件。是的,它应该是<=:)

答案 3 :(得分:0)

除了应该是txt.value.length <= maxLength之外,这应该是完全正常的(请查看这个小提琴https://jsfiddle.net/Aides/nc39hsng/

您也可以使用onkeyuponchange代替setInterval