javascript - Knockout.js: Set a default text if a binding has a given value - Stack Overflow

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742395814a4435919.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信