aleczandru
aleczandru

Reputation: 5459

Knockout checked property does not work as expected

Hi I am trying to use a checkbox with knockout and I seem to have a problem with the behavior it is having here is my code:

postModel = ko.observable('false');   
<input type="checkbox" data-bind="checked:postModel.closeSession" id="dummid" checked>
<span data-bind="text: postModel.closeSession"></span>

When I run my app this is what I get:

enter image description here

Which is what I expect to get.But when I click on the checkbox I expected it to change the observables value to true but this is what I get:

enter image description here

Another click and it seems the observable changes it's value to true:

enter image description here

If I click again the observable is false again.

My expectation were that when the checbox is checked the observable is set to true and when is not checked it is set to false.

Am I doing something wrong or is this how the checked property should work?

Upvotes: 3

Views: 59

Answers (1)

hutchonoid
hutchonoid

Reputation: 33306

If you define the property on your view model/ markup as follows it will work as expected.

JS

var ViewModel = function()
{
     self = this;
     self.closeSession = ko.observable(true);
}

var viewModel = new ViewModel();
ko.applyBindings(viewModel);

Markup

<input type="checkbox" data-bind="checked:closeSession" id="dummid" checked>
<span data-bind="text: closeSession"></span>

JsFiddle

Check the box in the below fiddle to see the text updating to the correct value.

http://jsfiddle.net/LnwQt/1/

Upvotes: 3

Related Questions