In knockout.js I have a very standard field that looks like this:
<label data-bind="text: JobTitle"></label>
What I'd like is to have a default value specified in here if the text value is null, for example "No Job Title Specified".
Is this possible to do in knockout.js?
Thanks.
Binding syntaxThe binding name should generally match a registered binding (either built-in or custom) or be a parameter for another binding. If the name matches neither of those, Knockout will ignore it (without any error or warning). So if a binding doesn't appear to work, first check that the name is correct.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
The shortest / easiest way is probably:
<label data-bind="text: JobTitle()||'No Job Title Specified'"></label>
Working example:
var ViewModel = function() { this.jobTitle = ko.observable(); }; ko.applyBindings(new ViewModel());
body { font-family: arial; font-size: 14px; } .liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; } .liveExample input { font-family: Arial; } .liveExample b { font-weight: bold; } .liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; } .liveExample select[multiple] { width: 100%; height: 8em; } .liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div class='liveExample'> <p>Job Title: <input data-bind='value: jobTitle' /></p> <h2 data-bind="text: jobTitle()||'No Job Title Specified'"></h2> </div>
Or JS Fiddle: http://jsfiddle.net/735qC/43/
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