Use Twitter Bootstrap button group as radio select with knockout bindings

后端 未结 2 1210
旧时难觅i
旧时难觅i 2021-02-09 02:32

This is working:

view.html

相关标签:
2条回答
  • 2021-02-09 03:08

    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

    0 讨论(0)
  • 2021-02-09 03:12

    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.

    0 讨论(0)
提交回复
热议问题