Reputation: 833
I have a select, and am trying to show a property when the select is changed (when a donation type is selected, I'd like to show a more lengthy description of the donation type). Unfortunately, it's not working; I can't see to access the properties of the view model's selectedDonation property.
I have a fiddle that should help illustrate what I'm trying to do. This is my first actual attempt at incorporating knockout.js into a project, so please excuse beginner mistakes.
My select looks like this:
<select data-bind="options: availableDonationTypes, optionsCaption: 'Please select...', value: selectedDonation.donationType, optionsText: 'label'"></select>
I'm trying to show the description here, but the ternary expression always evaluates to false. What am I doing wrong?
<span data-bind="text: selectedDonation() ? selectedDonation().donationType().description : 'No type selected'"></span>
If I use selectedDonation instead of selectedDonation() as the test, the expression evaluates to true, but I still can't find a way to access the selected donation type's description.
My viewmodel and object:
function Donation(donationType, donationAmount) {
var self = this;
self.donationAmount = donationAmount;
self.donationType = ko.observable(donationType);
self.formattedAmount = ko.computed(function () {
var amount = self.donationAmount;
return amount ? "$" + amount.toFixed(2) : "None";
});
}
function DonationsViewModel() {
var self = this;
self.availableDonationTypes = [{
label: "Donation 1",
description: "This is donation number 1."
}, {
label: "Donation 2",
description: "This is donation number 2."
}];
self.selectedDonation = ko.observable();
self.donations = ko.observableArray([
new Donation(self.availableDonationTypes[0], 50),
new Donation(self.availableDonationTypes[1], 75)]);
self.totalDonation = ko.computed(function () {
var total = 0;
for (var i = 0; i < self.donations().length; i++)
total += self.donations()[i].donationAmount;
return total;
});
self.addDonation = function (form) {
self.donations.push(new Donation(self.selectedDonation.donationType, parseInt(self.selectedDonation.donationAmount)));
}
self.removeDonation = function (donation) {
self.donations.remove(donation);
}
}
Upvotes: 0
Views: 142
Reputation: 19847
You're problem is that selectedDonation
starts out as nothing. You can't bind the value of the dropdown to the dontationTypee property of nothing: it doesn't have such a property.
selectedDonationneeds to be a
Donation` object.
Here is the final fiddle using that method: http://jsfiddle.net/xUn9N/3/
Upvotes: 1