user1390429
user1390429

Reputation: 117

Binding checkboxes to array with Knockout.js (MVC Razor)

I have a Knockout.js view model that looks like this:

"UserName":null,
"FirstName":null,
"LastName":null,
"Countries":{
    "arrCountries":[]
}

And a set of country checkboxes that all must be rendered with the same data-bind value (I'm using this custom CheckBoxListFor helper, which can apply custom HTML to each checkbox, but it's the same custom HTML for each checkbox. It takes a property that lists every available country from my razor view model to create the checkboxes, and then renders some as marked based on another razor view model property).

The checkbox values are integers (1, 2, 3, etc) and it's those integers that I'd like to throw into the arrCountries property of the view model.

Here's how a checkbox is rendered as it stands at the moment:

<input checked="checked" data_bind="checked: ???" id="Countries.arrCountries107" name="Countries.arrCountries" type="checkbox" value="1"></input>

I've proven the concept of using viewModel.Countries.arrCountries.push(1); to update the view model (followed by an alert that gives me a count of the elements in arrCountries to prove that the push worked), but I can't seem to get the data-bind HTML property on the checkboxes to wire up so that they check and uncheck as I send push and remove commands.

Any help much appreciated!

Upvotes: 3

Views: 6529

Answers (1)

Paolo del Mundo
Paolo del Mundo

Reputation: 2121

Make the checked data attribute point to the selected countries. If the checkbox's value is in the array of checkboxes, then it will be checked. It won't otherwise.

<input checked="checked" data-bind="checked: Countries" type="checkbox" value="3"></input>

Take a look at this fiddle I put up.

http://jsfiddle.net/u8xP9/3/

Upvotes: 8

Related Questions