How to build a textarea with character counter and max length?

独自空忆成欢 提交于 2019-12-04 02:58:08

Using a computed value only partially solves the problem. Disabling the textarea based on that computed value (as was done in Michael Berkompas's fiddle) doesn't really solve the problem. You need to use a custom binding to make this work. Using that fiddle as a starting point, we can use custom bindings to round it out:

http://jsfiddle.net/ReQrz/1/

Which is something like:

ko.bindingHandlers.limitCharacters = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel)
    {
       element.value = element.value.substr(0, valueAccessor());
       allBindingsAccessor().value(element.value.substr(0, valueAccessor()));
    }
};

And then doing:

<textarea data-bind="value: comment, valueUpdate: 'afterkeydown', limitCharacters: 20"></textarea>
Michael Berkompas

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​​​​​​​

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

This works for me in 3.0.0

    ko.bindingHandlers.maxLength = {
        update: function(element, valueAccessor, allBindings){
            if(allBindings().value()){
                allBindings()
                  .value(allBindings().value().substr(0, valueAccessor()));
            }
        }
    }
  <textarea data-bind="value: message, 
                       maxLength: 255, 
                       valueUpdate: 'afterkeydown'"></textarea>

Why not in the view do something like this:

<textarea data-bind="event: { keypress: enforceMaxlength }></textarea>

With this in the viewModel?

function enforceMaxlength(data, event) {
        if (event.target.value.length >= maxlength) {
            return false;
        }
        return true;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!