0

Here's a snippet from a knockout based answer editor

<!-- ko foreach: Answers -->
<div class="qa-box" data-bindx="event: { mousedown: mouseDown, dragend: dragEnd, dragstart: dragStart }">
  <div class="qa-body">
    <div class="radio">
      <label>
        <input type="radio" data-bind="attr: { name: 'Q' + $parentContext.$index(), value: $index }, checked: $parent.CorrectAnswer" /><span></span>
        Tick the correct answer
        <span data-bind="text:$parent.CorrectAnswer"></span>
      </label>
      <a href="#" data-bind="click: $parent.remove.bind($parent)">
        <i class="fa fa-times"></i>
        Remove this answer
      </a>
      <div class="form-control" contenteditable="true" data-bind="ckeditor: $data, attr: { id: 'Q' + $parentContext.$index() + 'A' + $index() }"></div>
    </div>
  </div>
</div>
<!-- /ko -->
<div>CorrectAnswer: <span data-bind="text: CorrectAnswer"></span></div>

You'll notice I put a bound span on the end of the radio button label so I can see what happens to the CorrectAnswer observable when I interact with the UI. This is how I know it's correctly bound to the view model. Clicking a radio button or its label changes the value of CorrectAnswer exactly as intended.

This also allows me to know that CorrectAnswer contains the value I expected.

Let's take a closer look at the binding in case it isn't obvious.

attr: { name: 'Q'+$parentContext.$index(), value: $index }, checked: $parent.CorrectAnswer

All the answers for a given question get the same name Qx and a value provided by the item's list position. When an item is clicked its list position is written to CorrectAnswer. This does happen, as evidence by the new value showing up in the telltale div.

So, what could be preventing the UI from initialising as checked when everything else is fine?

Peter Wone
  • 17,965
  • 12
  • 82
  • 134

1 Answers1

2

It isn't an initialisation problem, it's a type compatibility problem. The value of a radio input is of type string. The value provided by my view model is of type number. Knockout does a strong comparison and does not recognise a match.

See also Radio buttons Knockoutjs

Community
  • 1
  • 1
Peter Wone
  • 17,965
  • 12
  • 82
  • 134