I have two observablearrays in my ViewModel:
- ShortlistedCountries
- CompanyMainList
All companies names are displayed in a dropdown box. And the shortlisted companies are listed underneath it.
I would like to achieve two things from this demo.
Firstly, the users should be able to select the company name from the dropdown and add it to the Shortlisted company list.
Secondly, the users should get an error message (or alert) if they try to shortlist a company that has already been added to the shortlisted companies list.
Please have a look at my demo in JSFiddle
HTML
<div>
<div>All Companies</div>
<div>
<div id="rdoCompanyServer">
<select data-bind="options:CompanyMainList, optionsText:'CompanyName', optionsValue:'id', optionsCaption: 'Select a company...'"></select> <a href="#" data-bind="click:AddToShortlistedCountries">Add to Shortlist</a>
</div>
</div>
</div>
<br/>
<br/>
<br/>
<div>
<div id="sectionHeading">My Shortlisted Companies</div>
<div>
<div>
<ol data-bind="foreach: ShortlistedCountries">
<li><span data-bind="text:CompanyName"></span><span id="removeshortlist">
<a href="#" data-bind="click: $parent.DeleteShortlistedCountries">Remove</a></span>
</li>
</ol>
<br />
</div>
</div>
</div>
Knockout JS
function CompanyViewModel() {
var self = this;
self.currentDemoLicenses = ko.pureComputed(function () {
return self.demoLicenses().length;
});
/* adding bookmark servers in the same view TEST */
self.bookmarkedServerCount = ko.pureComputed(function () {
return self.ShortlistedCountries().length;
});
self.ShortlistedCountries = ko.observableArray([{
CompanyName: 'Apple Inc',
id: 11
}, {
CompanyName: 'TDK',
id: 15
}, {
CompanyName: 'Samsung',
id: 16
}
]);
self.DeleteShortlistedCountries = function (ShortlistedCountries) {
self.ShortlistedCountries.remove(ShortlistedCountries);
};
self.AddToShortlistedCountries = function () {
self.ShortlistedCountries.push(self.ShortlistedCountries);
};
self.CompanyMainList = ko.observableArray([{
CompanyName: 'Acer',
id: 1
}, {
CompanyName: 'Toshiba',
id: 12
}, {
CompanyName: 'Sony',
id: 13
}, {
CompanyName: 'LG',
id: 14
}, {
CompanyName: 'HP',
id: 6
}, {
CompanyName: 'Hitachi',
id: 6
}, {
CompanyName: 'Apple Inc',
id: 11
}, {
CompanyName: 'TDK',
id: 15
}, {
CompanyName: 'Samsung',
id: 16
}, {
CompanyName: 'Panasonic',
id: 7
}]);
};
$(document).ready(function () {
ko.applyBindings(new CompanyViewModel());
});
Have a look at my demo in JSFiddle
Please let me know if I am missing some thing or is there anything wrong with my code.
Thank you.
Kind regards.
Sid