The code bellow is supposed to do the following:
The issue is that when I remove one word (suppose the textbox's value is "Bill Gates" in default), and I removed "Gates", I want the span shows me "Bill" in real time not when I leave the field.
So how to make KnockoutJS support "Real Time" property changes? I want to see the span changing as I type instead of when leaving the textbox or press the "Enter" key.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Knock Out Sample</title>
</head>
<body>
Your Name, please: <input type="text" data-bind="value: myName" />
<br />
<span data-bind="text: myNameShown, visible: showWelcome" id="spName"></span>
</body>
<script src="KnockOutJS.js" type="text/javascript"></script>
<script type="text/javascript">
var model = {
myName: ko.observable("Bill Gates")
};
model.myNameShown = ko.dependentObservable(function () {
return "Welcome: " + model.myName();
}, model);
model.showWelcome = ko.dependentObservable(function () {
return model.myName() && model.myName().trim() != "";
}, model);
ko.applyBindings(model);
</script>
</html>
The answer by @Luis utilizing valueUpdate: 'afterkeydown' in combo with the value binding works great, but if you use Knockout 3.2 or higher there's a preferred alternative answer: use the textInput binding. This binding is more succinct, and handles cross-browser quirks. Use it like this:
ko.applyBindings({myName: ko.observable('initial value')});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Input: <input type="text" data-bind="textInput: myName" />
<hr />
Result: <strong data-bind="text: myName"></strong>
To quote aforementioned docs about the difference between textInput and value:
Although the value binding can also perform two-way binding between text boxes and viewmodel properties, you should prefer textInput whenever you want immediate live updates. The main differences are:
- Immediate updates [...]
- Browser event quirks handling [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With