Reputation: 1
I'm doing knockout js. I have an array list coming from the database by making an ajax call and saving all the values in knockout observable array.
I'm looping through the array. Based on a value I want to check or uncheck the checkbox. Below is how I'm doing but this does not seems to be working. I can see values for roleid exists in the array but the checkbox is not checked if the value of roleid is true. What am i doing wrong here.
<tbody data-bind="foreach:$root.test">
<tr>
<div><input type="checkbox" value="1" data-bind="checked: roleid == 1"/></div>
</tr>
</tbody>
Upvotes: 0
Views: 1450
Reputation: 8487
You can use checkedValue binding and can assign the observableArray to checked binding.
From documentation
If your binding also includes checkedValue, this defines the value used by the checked binding instead of the element’s value attribute. This is useful if you want the value to be something other than a string (such as an integer or object), or you want the value set dynamically.
Here is the javascript code:
function viewModel()
{
var self = this;
//the array list which you can get from the server
self.items = ko.observableArray([
{ item: '1' },
{ item: '2' },
{ item: '3' },
{ item: '4' }
]);
//the array of items which you want to be checked
self.chosenItems = ko.observableArray(
[
self.items()[1],
self.items()[3]
]
);
}
Html code
<div data-bind="foreach: items">
<input type="checkbox"
data-bind="checkedValue: $data, checked: $root.chosenItems" />
<span data-bind="text: item"></span><br />
</div>
And here is the Js fiddle demonstrating the use.
Upvotes: 1
Reputation: 56
this will work if roleid is an observable and is set to a string value.
knockout "checked" compares only string values vs string values, so the value inside value="1" is considered a string.
so your checkbox will be checked if roleid is setup like this
viewModel.roleid = ko.observable("1");
Upvotes: 0
Reputation: 1860
I think roleid needs to be observable. And then you can use
roleid() === 1
or
roleid() === true
whichever is appropriate for your case.
Upvotes: 2