Melt Down
Melt Down

Reputation: 61

Update checkbox in KO Array

Can anyone explain why the following code is not working. I'm just trying to toggle the value when the user clicks the check box, but the state of the checkbox never changes.

When I console out the values I can see the original value of val() -- I toggle the value, and then I can see the new value -- yet my checkbox doesn't update, it appears to be locked.

There are multiple checkboxes on the Form.

self.val = ko.observable();

self.updateCheckboxVal = function () {

return my.Update.updateCheckboxVal({ "id": self.logpropid(), "checkval": self.val() });


    };

My HTML Code:

<input data-bind="checked:val,click:function(){ updateCheckboxVal() }"    type="checkbox" />

Upvotes: 0

Views: 92

Answers (1)

TrueEddie
TrueEddie

Reputation: 2233

The only code you should need to bind your checked state to the value in your javascript is:

function MyViewModel()
{
    self.val = ko.observable();

    self.val.subscribe(function(newValue)
    {
        // Update Database
    });
}

ko.applyBindings(new MyViewModel());

And your HTML should look like:

<input type="checkbox" data-bind="checked: val" />

Edit:

Added the code for subscribing so you can update your database. Here is the knockout documentation on subscribing: http://knockoutjs.com/documentation/observables.html#explicitly-subscribing-to-observables

Upvotes: 1

Related Questions