I need to get a value from the database after page load is complete and run a function that will populate several dropdowns depending on the value that has been retrieved. Like a change event for a form control.
How can I do this using Knockout.js?
Thanks.
Here's a quick and dirty example. The idea is to:
getJSON
to retrieve data from your server.getJSON
. If I understand you correctly, you will not be retrieving the actual contents of the drop down list, but some other piece of information that will help you to decide what options will be shown. I incorporated this idea into the example.Btw, Countries does not have to be an array of strings. It can be an array of complex JS-objects. However, you'll have to expand your data-bind="options: ..."
binding with optionsText
and optionsValue
to indicate what property of your object is the label and value. Look here for more details.
var CompanyViewModel = function()
{
var self = this;
self.Countries = ko.observableArray();
$.getJSON('api/countries', function(data) {
if(data == 1)
{
self.Countries(['France', 'Germany', 'Spain'])
} else if(data == 2)
{
self.Countries(['Holland', 'Belgium', 'Luxemburg']);
}
});
}