Csaba Toth
Csaba Toth

Reputation: 10697

How to in-place edit boolean value with x-editable

I want to display a boolean value on a page (actually it'll be cells in a table), and it has to be editable. Furthermore, it's not a checkbox, but I spell out "false" and "true". We use bootstrap 3, and latest knockout. I decided to use x-editable Bootstrap 3 build. I also use a knockout custom binding: https://github.com/brianchance/knockout-x-editable.

I figured that to implement this I need to configure x-editable to be in popup mode, and select type. I also supply the selections ("true" and "false" only in this case) in a parameter. Almost everything is fine and dandy, except that the in-place dialog doesn't display the current value when it pops up. How can I fix that? I tried 'defaultValue' parameter, but it didn't help.

Here is the fiddle: http://jsfiddle.net/csabatoth/7ybVh/4/

<span data-bind="editable: value,
      editableOptions: { mode: 'popup', type: 'select',
      source: '[{ value: 0, text: &#34;false&#34; },
                { value: 1, text: &#34;true&#34; }]' }">
</span>

simple model:

function ViewModel() {
    var self = this;
    self.value = ko.observable(false);
}

Upvotes: 2

Views: 4227

Answers (1)

nemesv
nemesv

Reputation: 139758

The problem is that you have true and false Boolean values in your observable but x-editable uses the 0 and 1 values to represent the "true" and "false" selection.

This causes two problems:

  • when initialized x-editable does not know that "false" means 0 so no default value selected
  • if you select anything in your pop-up editor your value observable will contain the "0" and "1" strings and not the false and true Boolean values...

You can solve both problems with intoroducing a computed property which translates between the Boolean and numerical values:

self.computed = ko.computed({
    read: function() { return self.value() ? 1 : 0 },
    write: function(newValue) { self.value(newValue == '1') }
});

And you need to use this property in your editable binding:

<span data-bind="editable: computed,
      editableOptions: { mode: 'popup', type: 'select',
      source: '[{ value: 0, text: &#34;false&#34; },
                { value: 1, text: &#34;true&#34; }]' }">
</span>

Demo JSFiddle.

Upvotes: 3

Related Questions