如何使用字符计数器和最大长度来构建文本区域? [英] How to build a textarea with character counter and max length?

查看:63
本文介绍了如何使用字符计数器和最大长度来构建文本区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此jsfiddle .它包含以下内容:

Please consider this jsfiddle. It contains something along these lines:

<textarea data-bind="value: comment, valueUpdate: 'afterkyedown'"></textarea>

<br/><br/>
<span data-bind="text: getCount, valueUpdate: ['afterkeydown','propertychange','input']"></span> characters???

这个JavaScript:

And this JavaScript:

var viewModel = function(){
    var self = this;

    self.count = ko.observable(0);
    self.comment = ko.observable("");
    self.getCount = function(){
        var countNum = 10 - self.comment().length;
        self.count(countNum);
    };
}

var viewModel12 = new viewModel();
ko.applyBindings(viewModel);

我有一个textarea,最大长度应为20个字符.当字符数达到20时,它将停止,并且如果您尝试添加更多字符,则将其删除.

I have a textarea where the maxlength should be 20 characters. When the number of characters reaches 20, it will be stop, and if you try to add more characters, they will be removed.

请注意,这也适用于复制/粘贴:如果用户粘贴了20个以上的字符,则仅保留前20个字符,其余的应删除.

Note that this also has to work for copy/paste: if a user pastes more than 20 characters, only the first 20 will stay, and the rest of them should be removed.

推荐答案

看看此jsfiddle ,其工作原理如下:

Have a look at this jsfiddle, which works along these lines:

var viewModel = function(){
    var self = this;

    self.comment = ko.observable("");
    self.count = ko.computed(function(){
        var countNum = 10 - self.comment().length;
        return countNum
    });
}

var vm = new viewModel();
ko.applyBindings(vm);

<textarea data-bind="value: comment, valueUpdate: 'afterkeydown'"></textarea>
<br/><br/>
<span data-bind="text: count"></span> characters​​​​​​​

您需要了解 ko.computed()才能进行此类操作.

You need to learn about ko.computed() to do this sort of stuff...

这篇关于如何使用字符计数器和最大长度来构建文本区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆