Use Twitter Bootstrap button group as radio select with knockout bindings

馋奶兔 提交于 2019-12-03 06:48:31

The issue is that you are using Checked binding with button which is not allowed, instead you can use click binding. check this fiddle:

http://jsfiddle.net/a8wa8/7/

Updated:

Yes you can achieve this by using ko css binding. Check this updated fiddle:

Updated Fiddle

The checked binding only works with "checkable" controls like checkbox (<input type='checkbox'>) or a radio button (<input type='radio'>).

But you have button in your second example where bootstrap just emulates the look of the radio button group so the checked binding doesn't work.

However you can use the click binding where you pass the value to your observable:

<span class="btn-group" data-toggle="buttons-radio">
     <button data-bind="click: function() { priority2('want') }" 
             type="button" class="btn" value="want">I want to</button>
     <button data-bind="click: function() { priority2('need') }" 
             type="button" class="btn" value="need">I need to</button>    
</span>

And you can hide this behind a custom binding:

ko.bindingHandlers.valueClick = {
    init: function(element, valueAccessor, allBindingsAccessor, 
                  viewModel, bindingContext) {     
        var value = valueAccessor();
        var newValueAccessor = function() {
            return function() {
                value(element.value); 
            };
        };
        ko.bindingHandlers.click.init(element, newValueAccessor, 
            allBindingsAccessor, viewModel, bindingContext);
    },
}

Then you can use it like:

<span class="btn-group" data-toggle="buttons-radio">
     <button data-bind="valueClick: priority2" 
             type="button" class="btn" value="want">I want to</button>
     <button data-bind="valueClick: priority2" 
             type="button" class="btn" value="need">I need to</button>    
</span>

Demo JSFiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!