Knockout.js event that tracks every change of text inside an input text box

I am new to js knockout. I want to call a function every time the text changes inside the text field. I researched abit and implemented keyup, keydown and keypress, but they did not work properly. If anyone can give me a solution or redirect me to some document useful for my script. And if there is some kind of documentation about all the events (built-in and custom) available in Js knockout, that would be very helpful.

To clarify the problem:

data-bind="value: targetProp, event:{keyup: $parent.changeProp}" 

And in Js:

  Inside parent: this.changeProp = function () { if (condition..) { do something... } } 

It does not work with a key. For a simple solution, please give me something that will warn the length of the line that was written inside the text field (for each entered and deleted text). Thanks in advance.

+6
source share
4 answers

You can also subscribe to changes manually.

Make sure targetProp is observable, and when creating the parent, manually subscribe to the changes:

 parent.targetProp = ko.observable(originalValue); parent.targetProp.subscribe(function(newValue) { alert("The new value is " + newValue); }); 

Edit: to bind options:

 <select data-bind="options: myObservableArray, value: selectedValue"></select> 

in js:

 self.selectedValue = ko.observable(); 

then

 self.selectedValue.subscribe(function(newValue) { alert("The new value is " + newValue); }); 
+2
source

You can use valueUpdate: 'afterkeydown' , which updates your view model as soon as the user starts typing a character.

 data-bind="value: targetProp, valueUpdate: 'afterkeydown'" 
+8
source

Or you can use textInput binding from last KO 3.2

<input data-bind="textInput: userName" />

In addition to live updates, it handles cut / paste, drag and drop, auto-complete correctly.

+8
source

If you want to calculate in real time how a person types, you can do it.

HTML

 <input type="text" id="description" class="form-control" maxlength="255" data-bind="value:description, event:{keyup:calcDescriptionCount}"> <br> <span data-bind="text:descriptionCount"></span> charactors left. 

ViewModel JS

 self.description = ko.observable(""); self.descriptionCount = ko.observable(255); self.calcDescriptionCount = function(){ this.descriptionCount(255 - $("#description").val().length); }; 
0
source

Source: https://habr.com/ru/post/950454/


All Articles