Search code examples
javascriptdata-bindingknockout.js

Knockout observable field not updating on input value change


I have noticed that I cannot get some of the Knockout live tutorials working or basic examples that should demonstrate the observable data binding.

Here is my code:

<!DOCTYPE html> 
<html lang="en">

<html>
    <head>
        <meta charset="utf-8" />
        <title>Testing</title>
        <script type="text/javascript" src="knockout.js"></script>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            function TestViewModel() {
                this.Name = ko.observable("Testing");
            }

            $(function() {
                ko.applyBindings(new TestViewModel());
            });
        </script>
    </head>

    <body>
        <h1>Testing Knockout.js</h1>
        <div>
            <div>
                <span data-bind="text: Name"></span>
            </div>
            <div>
                <input type="text" data-bind="value: Name"></input>
            </div>
        </div>
    </body>
</html>

So when I open this up in Google Chrome or Firefox I would expect the value of the span tag to change as I change the text in the input, however this is not the case. Can someone please explain why the above does not work? (This code was pretty much copied from the documentation on the website)

Thanks, Alex.


Solution

  • As of KO version 3.2 (as Salvador Dali answer's pointed out) you should use the textinput binding for instant updates:

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

    In you are using an earlier Knockout version and the value binding, then you should make the following changes:

    By default knockout updates the value of the observables on the change event (e.g when the focus of the textbox is lost).

    If you want instant update you need to specify the valueUpdate option where the possible events are: keyup, keypress, afterkeydown see more info in the documentation.

    So change your value binding:

    <input type="text" data-bind="value: Name, valueUpdate: 'afterkeydown'"></input>
    

    Demo JSFiddle.