admin管理员组

文章数量:1336140

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) { '' }" />

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) { '' }" />
Share Improve this question edited Mar 1, 2017 at 10:30 Simon_Weaver 146k92 gold badges680 silver badges715 bronze badges asked Dec 14, 2012 at 10:24 pistacchiopistacchio 59k110 gold badges287 silver badges434 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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/d4SKr/

The correct answer should be to create a puted 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" />

本文标签: javascriptKnockoutjs Set a default text if a binding has a given valueStack Overflow