Question

The code below is what I have written for a checkbox. Not sure why this doesn't show the value as checked, even though its coming correctly from my JS file.

<input type="checkbox" 
       data-bind="attr: { value: person.id}, checked: $root.chosenPerson">

If the chosenPerson contains two values, these should be checked in the checkbox. This doesnt happen.

I also tried :

<input type="checkbox" 
       data-bind="attr: { value: person.id}, checked: $root.chosenPerson">

And I also tried:

<input type="checkbox" 
       data-bind="attr : { checked:$root.chosenPerson }, value : person.id" />

Nothing works in making the chosenPerson "checked".

Please suggest a solution.

Was it helpful?

Solution

Your binding should return true, so change it to this -

<input type="checkbox" data-bind="attr: { value: person.id}, checked: $root.chosenPerson() === $data">

Where chosenPerson is equal to the context of the input element. If the element is not within the context of a person, just do

<input type="checkbox" data-bind="attr: { value: person.id}, checked: $root.chosenPerson() === person()">

OTHER TIPS

If your chosenPerson array contains integers, the value of the checkbox must also be an integer. This isn't possible using the attr/value binding because it just set the value attribute of the element, which will always be a string. Instead you should use the checkedValue binding, which can bind any type of value.

<input type="checkbox" data-bind="checkedValue: person.id, checked: $root.chosenPerson">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top