简体   繁体   中英

Knockout checkbox - Push only checked values into array

I have this checkbox control that dynamically populates

<!-- ko foreach: AllPens -->
<label>
    <input type="checkbox" data-bind="checked: IsChecked" />
    <span data-bind="text: name"></span>
</label>
<!-- /ko -->

Assuming the observable array GETs (AllPens)

{ code: "001" , name: "Parker"},
{ code: "002" , name: "Sheaffer"},
{ code: "003" , name: "Mont Blanc"}

I have to POST back an array of the checked elements -

"Pens": [{
    "PenType": "001",
    "Order": false
}, {
    "PenType": "002",
    "Order": true
}]

I have a rough idea to store the checked Pen's code and if ischecked in an object - new Pen('001',true)

function Pen(type, checked) {
    var self = this;

    self.PenType = ko.observable(type);
    self.IsChecked = ko.observable(false);
}

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

I believe the below should work if i figure out the above.

self.Pens= ko.computed(function()
{
    var selectedPens = [];
    ko.utils.arrayForEach(self.Pen(), function (pen) {
        if(pen.IsChecked())
            selectedPens.push(pen);
    });
    return selectedPens;
});

I'm still learning KO. Any help is appreciated :)

I managed to get this working.

Rather than dynamically populating the key value pairs directly to Self.AllPens(), I created a function to load the list of Pens into an Object

    function Pen(type,name,checked) {
        var self = this;

        self.PenType= ko.observable(type);
        self.Name = ko.observable(name);
        self.IsChecked = ko.observable(checked || false);            
    }

And looped through to check for IsChecked below -

        self.Pens= ko.computed(function () {
            var selectedPens = [];
            ko.utils.arrayForEach(self.AllPens(), function (pen) {
                if (pen.IsChecked()) {
                    selectedPens.push({
                        PenType: pen.penType,
                        Order: pen.IsChecked()
                    });
                }
            });
            return selectedPens ;
        });

You code should be like this

self.checkedPens = function(pen) {
    var isChecked = pen.order === "true";
    if (pen.penType !== null && isChecked) {
        self.Pens.push({
            PenType: pen.penType,
            Order: isChecked
        });
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM