Binding to Bootstrap 3 checkboxes (DOM property bindings)

1,106 views
Skip to first unread message

taco.p...@gmail.com

unread,
Sep 2, 2013, 9:40:18 AM9/2/13
to knock...@googlegroups.com
Hello,

I had issues that the KO.js checked binding doesnt work for checkboxes in a Bootstrap 3 btn-group.

The Bootstrap 3 checkboxes inside a btn-group are toggled on/off via their DOM property checked.

                    <div class="btn-group" data-toggle="buttons">                   
                        <label class="btn btn-default">
                            <input type="checkbox" data-bind="checkedProp: observable1" /> 
                            Observable 1
                        </label>
                        <label class="btn btn-default">
                            <input type="checkbox" data-bind="checkedProp: observable2" /> 
                            Observable 2
                        </label> 
                    </div>

This custom binding supports the Bootstrap 3 btn-group checkboxes:

        ko.bindingHandlers.checkedProp = {
            init: function(element, valueAccessor) {
                Object.defineProperty(element, 'checked', {
                    set: function(newValue) {
                        var value = valueAccessor();
                        value(newValue);
                    }
                });
            },
            update: function(element, valueAccessor) {
                var value = ko.unwrap(valueAccessor());
                element.checked = value;
            }
        };

I hope this can help anyone who has the same binding issues.

neil.li...@gmail.com

unread,
Dec 6, 2013, 2:53:28 PM12/6/13
to knock...@googlegroups.com, taco.p...@gmail.com
I thought this was what I was looking for. While I'm glad to see some other approach than what I've been trying all morning I am looking to get the value from:
<div class="btn-group" data-toggle="buttons">

   
<label class="btn btn-primary">
       
<input type="checkbox" value="spicy" data-bind="checkedBox:platforms" />spicy
   
</label>
   
<label class="btn btn-primary">
       
<input type="checkbox" value="hot" data-bind="checkedBox:platforms" />hot
   
</label>
   
<label class="btn btn-primary">
       
<input type="checkbox" value="taco" data-bind="checkedBox:platforms" />taco
   
</label>
</div>
<br/>Checked: <span style="color:#000" data-bind="text:platforms"></span>


I'll log-up what you did and hopefully find the answer soon. I'll need to read into what valueAccessor is all about.

Thanks!
Reply all
Reply to author
Forward
0 new messages