Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout dropdown

Tags:

knockout.js

I am having trouble getting the selected item of a bound drop down list.

<p>
  Your Group: 
  <select data-bind="options: availableGroups, optionsText: 'Name', optionsValue: 'GroupId', value: selectedGroup, optionsCaption: 'Choose...'"></select>
</p>
<p>
  I am visible
  You have chosen <span data-bind="text: selectedGroup() ? selectedGroup().Name : 'Nothing'"></span>
</p>

When I choose something from the drop down list, I would like to get the text of the selection, not the value. I am very new to knockout and trying to get a handle on this. I've created a fiddle for this.

http://jsfiddle.net/voam/FjRxn/

like image 349
voam Avatar asked Jan 30 '26 02:01

voam


1 Answers

For your original question @Pete's answer is right, but since you need to preserve GroupId as the value you could do this (modified fiddle).

First the selectedGroup property was renamed to selectedGroupId.

Then a new computed observable selectedGroup was defined based on the selectedGroupId:

self.selectedGroup = ko.computed(function () {
  for (var i = 0; i < groups.length; i++) {
    if (groups[i].GroupId == self.selectedGroupId())
      return groups[i];
  }
  return null;
});

Also the var self = this was defined

like image 59
pomber Avatar answered Jan 31 '26 17:01

pomber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!