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?

2 Answers 2

1

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

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

Updated fiddle

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.