Stranger
Stranger

Reputation: 862

Binding two values to an input field using knockout.js

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?

Upvotes: 0

Views: 1187

Answers (2)

babich.ss
babich.ss

Reputation: 177

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

Upvotes: 0

Paul Manzotti
Paul Manzotti

Reputation: 5147

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

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

Updated fiddle

Upvotes: 1

Related Questions