KnockoutJS: How do I access Selected Value from a Select Options after binding?

Hello my Sitepoint friends!
I am binding data to a Select Options tag as illustrated in the code below:

 function viewModel(){
     var self = this;
   
     var data = [{

         "LastName": "Jordan",
            "FirstName": "Michael",
            "Team": "Chicago Bulls",
            "Jersey": "23"
    }, {
        "LastName": "Duncan",
            "FirstName": "Tim",
            "Team": "San-Antonio Spurs",
            "Jersey": "21"
    }
         ];

   self.PlayersData = ko.observableArray($.map(data,
    
       function(item) {
        return { 
            FullName: item.FirstName + ' ' + item.LastName, value: item.Jersey } 
        }));

     // How do I pass the selected player Jersey here so 
   // that I can pass as argument to other functions?
     self.SelectedPlayer = ko.observable();

 } 

 ko.applyBindings(viewModel());

HTML:

<select class="form-control" 
  data-bind="options: PlayersData,
             optionsText: 'FullName',         
             value: SelectedPlayer"></select>

<!-- For demo only. I need to get the SelectedPlayer().value passed to a variable-->
<span data-bind="text: SelectedPlayer() ? SelectedPlayer().value : 'UNKNOWN'"></span>.

Here is a codepen: with the full working code.

How do I get the Jersey number based on selected item? I do not want to use a hidden field.

UPDATE:

Possible working solution:

Simply subscribed to the SelectedPlayer like this:

     self.SelectedPlayer.subscribe(function (newValue){
    alert(newValue.value);
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.