donpisci
donpisci

Reputation: 349

Initialising Knockout checkbox value

I think this may be more of a language problem as opposed to a framework issue, but here goes:

I'm having trouble setting the initial value of a checkbox.

Ive added a jsFiddle

Thanks!

Here is the troublesome code:

var allPrices = [
        { month: 'January', prices: [ (3, true), (4, false), (4, false), (4, false)] },
        { month: 'February', prices: [(3, true), (4, false), (4, false), (4, false)] },
        { month: 'March', prices: [(3, true), (4, false), (4, false), (4, false)] }
    ]        

//--Page ViewModel
var id = 1;

//--Set the structure for the basic price object
function Price(quote, isChecked) {
    this.quote = ko.observable(quote);
    this.valid = true;
    if (isNaN(quote)) {
        this.valid = false;
    }
    this.selected = ko.observable(isChecked);
    this.id = id;
    id++;
}

Upvotes: 1

Views: 143

Answers (1)

nemesv
nemesv

Reputation: 139748

With the syntax (3, true) you are using the Comma Operator and not creating an object.

The comma operator evaluates to its second argument (in this case to true) so it does not create an object with the value 3 and true as you would have been probably expected.

You need use the {} to create an object and you also need some property names, so you need to rewrite your prices to:

prices: [ 
    { quote: 3, isChecked: true}, 
    { quote: 4, isChecked: false}, 
    { quote: 4, isChecked: false}, 
    { quote: 4, isChecked: false} ]

And you need to change prices creation to

this.prices = ko.utils.arrayMap(prices, function (item) { 
     return new Price(item.quote, item.isChecked); 
 });

becase the callback function of the arrayMap takes on argument: the current item, and you can access the quote and isChecked from that current item.

Demo JSFiddle.

Upvotes: 1

Related Questions