0
votes

I have a list of checkboxes, which hide and display a number box when clicked. Here's the JSfiddle of that working: http://jsfiddle.net/bjornmann/yXUqf/3/

the basic idea is:

$('.numberthing').each(function(){push the data to an array here.})

Then I said "let's learn knockout and move this whole app into that framework" so that's when the bottom dropped out.

I have a list of items (the checkboxes) pushing to an array, and then a ko foreach in the view, but I'm lost on how to add in the data from the number box.

I'm having a hell of a time figuring out how to bind the value of an input to the value of the checkbox in an array in knockout.

1
I'm not sure what the down vote is for, but if you need me to make this more general I can... - Bjorn2Run
I think its really bad form to down vote with out a reason! Seems like a fine question to me. - Des Horsley

1 Answers

0
votes

Bindings in KO are two-way; If you update the view model, the UI gets updated. If you update the bound controls, the view model gets updated.

You can also make computed properties, which gets updated whenever any referenced observables gets updated.

function ViewModel(data) {
    data = data || {};
    this.checkboxes = ko.observableArray(
        ko.utils.arrayMap(data.checkboxes, function (title) {
            return new CheckboxModel(title);
        })
    );
    this.checkedCheckboxes = ko.computed(function () {
        return ko.utils.arrayFilter(this.checkboxes(), function (cb) {
            return cb.checked();
        });
    }, this);
}

function CheckboxModel(title) {
    this.title = ko.observable(title);
    this.checked = ko.observable(false);
    this.number = ko.observable(1);
}

$(function() {
    ko.applyBindings(new ViewModel({
        checkboxes: [ 'Champion', 'Reserve champion',
            '1st', '2nd', '3rd', '4th', '5th', '6th',
            '7th', '8th', '9th', '10th', 'Other']
    }));
});
​    ​
<div data-bind="foreach: checkboxes" id="cblist">
    <label data-bind="visible: checked">
        <input type="number" data-bind="value: number"/>
        <span data-bind="text: title"></span>
    </label>
    <label data-bind="visible: !checked()">
        <input type="checkbox" data-bind="checked: checked"/>
        <span data-bind="text: title"></span>
    </label>
    <br/>
</div>

http://jsfiddle.net/MizardX/zHTRP/