Josh
Josh

Reputation: 702

How to bind checkbox value to Knockout observableArray on an object?

I have something like this:

var ScheduleDay = function(day, times) {
    var self = this;
    self.day = ko.observable(day || "");
    self.times = ko.observableArray(times || []);
};

function viewModel() {
    var self = this;
    self.schedule = ko.observableArray([
        new ScheduleDay("Monday"),
        new ScheduleDay("Tuesday"),
        new ScheduleDay("Wednesday"),
        new ScheduleDay("Thursday"),
        new ScheduleDay("Friday"),
        new ScheduleDay("Saturday"),
        new ScheduleDay("Sunday")
    ])
}

ko.applyBindings(new viewModel());

<input id="mondaySchedule" type="checkbox" data-bind="checked ???">

I have 3 checkboxes for each day of the week: morning, afternoon, and evening. I would like a model that is something like: schedule:{Monday:["morning","afternoon"], Tuesday: ["afternoon"], etc.}

Upvotes: 1

Views: 3869

Answers (1)

Rango
Rango

Reputation: 3907

As you have specified your question in comments, I suggest to take a look at this simple markup, that will do what you want:

<ul data-bind="foreach: schedule">
    <li>
        <strong data-bind="text: day"></strong>
        <input type="checkbox" data-bind="checked: times" value='morning' /> Morning
        <input type="checkbox" data-bind="checked: times" value='afternoon' /> Afternoon
        <input type="checkbox" data-bind="checked: times" value='evening' /> Evening
    </li>
</ul>

Working example: http://jsfiddle.net/qjzbossb/

Upvotes: 5

Related Questions