user1857756
user1857756

Reputation: 385

knockout the "check" binding not working

I am new to knockout, I have found an example of checkbox binding which could be very useful in my website. Link to the example: http://knockoutjs.com/documentation/checked-binding.html

I tried to apply it to my page but it didn't work, then I tried to copy this example without changing anything but still it didn't work. I tried it on different browser(Chrome, Firefox, IE) and including different version of knockout libraries, but still it didn't work. I have no other idea what I am doing wrong, please help!

Here is the code of this example:

<!DOCTYPE html>
<head>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js'></script>


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dokument bez tytułu</title>
</head>

<body>
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
Preferred flavors of spam:
<div><input type="checkbox" value="cherry" data-bind="checked: spamFlavors" /> Cherry</div>
<div><input type="checkbox" value="almond" data-bind="checked: spamFlavors" /> Almond</div>
<div><input type="checkbox" value="msg" data-bind="checked: spamFlavors" /> Monosodium Glutamate</div>
</div>

<script type="text/javascript">
var viewModel = {
    wantsSpam: ko.observable(true),
    spamFlavors: ko.observableArray(["cherry","almond"]) // Initially checks the Cherry and Almond checkboxes
};

// ... then later ...
viewModel.spamFlavors.push("msg"); // Now additionally checks the Monosodium Glutamate  checkbox
</script>
</body>
</html>

Upvotes: 1

Views: 1999

Answers (1)

Matt Burland
Matt Burland

Reputation: 45135

What you are looking at is a fragment, not a fully working example. You need to do a couple of things.

You need to applyBindings:

ko.applyBindings(viewModel);

And you need to do that after the DOM has loaded (or knockout will get very upset).

Here's an example

I've updated my example a little to make it easier to see that the checkboxes are, in fact, bound. There's a list of the spamFlavors under the list of checkboxes that will change as you check and uncheck the checkboxes.

Upvotes: 1

Related Questions