Radio buttons rendered with a template not checked according to binding on load?

552 views
Skip to first unread message

Oliver Boermans

unread,
Feb 29, 2012, 11:13:47 PM2/29/12
to KnockoutJS
I’m rendering a set of radio buttons with a native knockout template:

HTML and JS snippets:
http://jsfiddle.net/Udt63/1/

My problem is the value I am assigning with a checked binding is not
resulting in a checked radio button on the initial render.

The binding is otherwise successful: if I change the data model after
they are rendered the corresponding radio button becomes checked.
Additionally other elements on the page which are bound to the same
value are correctly rendered. Clicking the radio buttons also results
in changes to the data model as expected.

Is it necessary for me to set an explicit checked="" attribute in the
rendered HTML? Or is there something I need do to differently to
ensure the radio button corresponding with my bound value is checked?

Cheers
Ollie
--
@ollicle

Ollie Boermans

unread,
Mar 1, 2012, 12:24:50 AM3/1/12
to KnockoutJS
I’m still interested in understanding why the native template did not
work, but using an Underscore template did:
http://jsfiddle.net/Udt63/2/

i.e. the radio button whose value corresponds with my bound value is
checked upon render.

Ollie
--
@ollicle

NTB

unread,
Mar 5, 2012, 12:27:34 PM3/5/12
to knock...@googlegroups.com
I can't say for sure whether this is true, as I haven't debugged the KO code, but I've had similar problems but with pre-selected values for dropdowns -- the case where the options for the dropdown are loaded asynch after the data has been bound.  It looks like in my scenario (which might be totally unrelated), if the framework can't find a match immediately to what's bound in the template, it will null out the value of the selected item observable.  I solved my scenario by setting the value of the selected observable again in the ajax callback after the select options were bound.

Oliver Boermans

unread,
Mar 21, 2012, 10:34:43 PM3/21/12
to knock...@googlegroups.com
For anyone who may later stumble on upon this thread.

Ultimately my solution to this was to template and render the HTML
(using mote.js) *before* applying the knockout binding. Using the same
data for the template as is used as a basis for the knockout ViewModel
means there was little redundancy.

Ollie
--
@ollicle

Reply all
Reply to author
Forward
0 new messages