0
votes

How do I get the selected value of a select?

HTML:

<select data-bind="options: customers, optionsText: 'customer_display_name', optionsValue: 'customer_id'"></select>

Javascript:

var customers = <?php echo json_encode($this->customers); ?>;
self.customers = ko.mapping.fromJS(customers);

How can I access the currently selected "optionsText" or "optionsValue" inside my ViewModel?

self.customers...?
1
Your binding says the value is bound to customer_id so you would use that.Jason Spake

1 Answers

0
votes

You can do it like this:

function ViewModel() {
  this.selectedCustomer = ko.observable();
  this.customers = [{
    customer_display_name: "Bob",
    customer_id: 10 
  }, {
    customer_display_name: "Joseph",
    customer_id: 20 
  },{
    customer_display_name: "Charlie",
    customer_id: 30 
  }];
  
  // Only for debug purposes
  this.selectedCustomer.subscribe(function (newValue) {
    console.info(newValue);
  }, this);
}
ko.applyBindings(new ViewModel());  
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<select data-bind="options: customers, optionsText: 'customer_display_name', optionsValue: 'customer_id', value: selectedCustomer"></select>

An observable selectedCustomer holds a value of 'customer_id' property of currently selected customer. If you want selectedCustomer to hold a whole object of currently selected customer, simply remove a property "optionsValue: 'customer_id'" from your HTML code.