RadioButtonList with Knockout

Homer picture Homer · Aug 11, 2012 · Viewed 10.7k times · Source

I need a RadioButtonList with a bunch of on/off choices similar to the CheckBoxList. I need it to translate to an on/off for each option, but Knockout resolves a group of radio buttons down to one value. Suggestions?

Example: http://jsfiddle.net/DPnBE/2/

Answer

Homer picture Homer · Aug 15, 2012

I did a custom binding. You could probably get rid of the for loop by storing the previously selected item somewhere. Then you just have to select and unselect 2 items.

Updated Example: http://jsfiddle.net/DPnBE/5/

ko.bindingHandlers.radioCheck = {
    init: function(element, valueAccessor) {
        //initalize checked value of element
        element.checked = valueAccessor()();

        //attach event to handle changes
        $(element).change(function(e) {
            var item = ko.dataFor(element);
            var items = ko.contextFor(element).$parent.items;
            for (var i = 0; i < items.length; i++) {
                //set selected() for all items
                //true for the checked element, false for the rest
                items[i].selected(items[i] == item);                
            }
        });        
    }
};