pistacchio pistacchio - 2 months ago 8
Javascript Question

Knockout.js: Set a default text if a biding 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) { '' }" />

Answer

You can use ? operator in data-bind attribute:

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