Alex Hope O'Connor
Alex Hope O'Connor

Reputation: 9714

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.

Upvotes: 29

Views: 33421

Answers (3)

Rafe Smith
Rafe Smith

Reputation: 79

For those who wander in here (like me) wondering why it isn't working. Be mindful of your extra '()' usage. This got me in trouble with a nested observable like this:

Bad:

<input data-bind="textInput: subItem().userName()" />

Good:

<input data-bind="textInput: subItem().userName" />

Upvotes: 2

nemesv
nemesv

Reputation: 139798

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.

Upvotes: 61

Salvador Dali
Salvador Dali

Reputation: 222939

The accepted answer is correct, but in a new KO version 3.2 they added textinput binding. So instead of value binding you can use textInput:

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

It does two important things:

  • make immediate updates
  • handles browser differences for cut, drag, autocomplete ...

Upvotes: 20

Related Questions