4

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 :)

2 Answers 2

3

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 ;
        });
Sign up to request clarification or add additional context in comments.

Comments

0

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
        });
    }
};

2 Comments

Should I be using $parent.chosenItems to check if the the checkbox is checked?
I think yes but not sure first try to debug your code or try check with console if you getting correct value than you can use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.