Description
Hi, I am using knock out. I have three checkboxes and an input field. When I click on checkbox, the value of the checkbox should appear on the input field. However, instead of getting the value of the checkbox, I see NaN.
jsFiddle link
function ViewModel() {
var self = this;
self.primaryClass = ko.observable("50");
self.secondaryClass = ko.observable("40");
self.otherClass = ko.observable("10");
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());
Check this out:
http://jsfiddle.net/Dtwigs/uFQdq/5/
Do your inputs like this to make them dynamic:
<label>
<input data-bind="checked: selectedValues, value: primaryClass" type="checkbox"></input>
<span data-bind="text: primaryClass"></span>
</label>
Change your values to the values in text.
Looking at the code, on this line,
total += parseInt(item);
the variable item is the value of your checkboxes.
<input data-bind="checked: selectedValues" type="checkbox" value="primaryClass">500</input>
<input data-bind="checked: selectedValues" type="checkbox" value="secondaryClass">200</input>
<input data-bind="checked: selectedValues" type="checkbox" value="otherClass">100</input>
meaning you are trying to parseInt("primaryClass")
... and so on.
Try changing the value of the checkbox to numbers.
Like here: http://jsfiddle.net/2L4W9/