简体   繁体   中英

Knockout.js: Set a default text if a binding has a given value

I'd like to reset the value of an input field ( text='' ) whenever model.id is null.

How to bind the input value to respond to a certain value of an observable object? Something that would look like:

<input type="text" data-bind="text: if (model.value == null) { '' }" />

You can use ? operator in data-bind attribute:

<input type="text" data-bind="value: model.id() == null ? 'Default Value' : model.value()" />

In your viewmodel, initiate value of the property as follow :

var model.value = ko.observable('');

In HTML, you don't have to use confitional expression

data-bind="text: model.value"

check these codes

<input type="text" data-bind="value: id() == true? 'Value is Red' : value()" />


function viewModel() {
    this.id = ko.observable(true);
    this.value = ko.observable("Value is Green");
}
ko.applyBindings(new viewModel());

http://jsfiddle.net/d4SKr/

The correct answer should be to create a computed observable to get the label.

self.getLabel = ko.pureComputed(function() {
    return this.value() === null ? 'Value is red' : value();
});

<input type="text" data-bind="text: getLabel" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM