Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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);

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.

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.

like image 248
qinking126 Avatar asked Oct 19 '12 21:10

qinking126


People also ask

How can I set maximum length of textarea?

The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element. Attribute Value: number: It contains single value number which allows the maximum number of character in Textarea element. Its default value is 524288.

What is the maximum length of textarea?

By default, the maximum is 524,288 characters.


2 Answers

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>
like image 64
grigson Avatar answered Sep 24 '22 00:09

grigson


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

like image 30
Mike B Avatar answered Sep 22 '22 00:09

Mike B