Working with a list of checkboxes in knockoutjs

后端 未结 2 1060
南方客
南方客 2020-12-05 20:26

I\'m trying to get my head around Knockout.js and I\'m quite stuck when it comes to checkboxes.

Server side I\'m populating a set of checkboxes with their correspond

2条回答
  •  一生所求
    2020-12-05 21:16

    The checked binding expects to be passed a structure that it can read/write against. This could be a variable, an observable, or a writable dependentObservable.

    When passed an array or observableArray, the checked binding does know how to add and remove simple values from the array.

    Here is a sample that also includes a computed observable that contains the array as comma delimited values. http://jsfiddle.net/rniemeyer/Jm2Mh/

    var viewModel = {
        choices: ["one", "two", "three", "four", "five"],
        selectedChoices: ko.observableArray(["two", "four"])
    };
    
    viewModel.selectedChoicesDelimited = ko.computed(function() {
        return this.selectedChoices().join(",");
    }, viewModel);
    
    ko.applyBindings(viewModel);
    

    HTML:

    提交回复
    热议问题