I am very knew to Knockoutjs and I am trying to execute a service call on input select.
I the object looks like this:
var teamViewModel = {
teams: ko.observableArray([]),
clearTeams: function(){
this.teams.removeAll();
},
addTeam: function (id, name, isChecked) {
t = new team(id, name, isChecked);
this.teams.push(t);
}
};
The select box is being populated by calling this:
function GetAvailableTeams() {
var jqxhr =
$.getJSON('http://localhost/Service.svc/GetTeamsAll',
function (data) {
teamViewModel.clearTeams();
$.each(data.GetTeamsAllResult,
function (key, val) {
teamViewModel.addTeam(val.TeamId, val.TeamName, true);
});
ko.applyBindings(teamViewModel, document.getElementById("teamNameLabel"));
})
}
The function is called on pageload and referenced like this:
<select id="teamNameLabel" date-theme="f" data-bind="options: teams, optionsText: 'name', value: 'id'"></select>
How do i update the global variable TeamId when an option on the select statement is selected?
EDIT:
function GetAllUsersByTeam(){
var url = 'http://localhost/Service.svc/GetUsersByTeam/'+TeamId;
var jqxhr =
$.getJSON(url,
function (data)
{
colleagueViewModel.clearColleagues();
$.each(data.GetUsersByTeamResult, function (key, val) {
colleagueViewModel.addColleague(val.FirstName, val.LastName, val.EmailAddress, val.PhoneNumber, val.LocationName, val.CapabilityId, val.CoeId);
});
ko.applyBindings(colleagueViewModel, document.getElementById("colleaguesListView"));
})
}
There’s no need to use a global variable. You can add a
selectedTeamobservable to your view model, that represents the selected option:And then, bind the options’
valueto theselectedTeam, that is:Finally, to access the
idof the selected option, simply useteamViewModel.selectedTeam().id.Here’s a DEMO.