0

Description
I have 3 checkboxes and one input field. When a user selects the checkboxes, the values appear on the input field. However, when a user does not select any of the checkboxes, I want an alternative value to appear in the input field.

What I have so far
http://jsfiddle.net/uFQdq/8/

function ViewModel() {
    var self = this;  
    self.primaryClass = ko.observable("50"); 
    self.secondaryClass = ko.observable("40"); 
    self.otherClass = ko.observable("10"); 

    self.alternativeValue("200");     

    self.selectedValues = ko.observableArray([]);

    self.sum = ko.computed(function () {
        var total = 0;
        ko.utils.arrayForEach(self.selectedValues(), function (item) {
            total += parseInt(item);
        });
        return total;
    });
}

ko.applyBindings(new ViewModel());

Issue
The issue at hand is that NOTHING is being displayed in the input field. What am I doing wrong?

4

2 回答 2

1

It's because you've not made alternativeValue an observable:

self.alternativeValue = ko.observable("200");

Updated fiddle

于 2013-03-22T18:18:51.317 回答
0

I think that is what you really need: your fiddle, revision 10.

<input data-bind="checked: selectedValues" type="checkbox" value="50">50</input>
<input data-bind="checked: selectedValues" type="checkbox" value="40">40</input>
<input data-bind="checked: selectedValues" type="checkbox" value="10">10</input>

<br/>
Result:
<input data-bind="value: sum" type="text"></input>

/*You really don`t need an observables for values*/

var model = {
    selectedValues: ko.observableArray([])
}

model.sum = ko.computed(function () {
    var result = 0;

    model.selectedValues().forEach(function(value){
        result += parseInt(value, 10);
    });

    if (result === 0) {
        result = 200;
    }
    return result;
});

ko.applyBindings(model);
于 2013-03-23T08:48:21.340 回答