Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout.js - data-bind text default value

Tags:

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.

like image 577
Adam Levitt Avatar asked May 14 '12 03:05

Adam Levitt


People also ask

How do you bind data in KnockoutJS?

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.

What is two-way data binding in KnockoutJS?

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.

What is $data in Knockout?

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.


1 Answers

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/

like image 146
rjmunro Avatar answered Oct 07 '22 22:10

rjmunro