Show value instead of text in Knockout-bound dropdown

时光毁灭记忆、已成空白 提交于 2021-01-29 09:46:34

问题


I'm having an HTML dropdown, where I use Knockout.js to bind the options. With the dropdown, you can select ISO country codes. In the (short) dropdown, I want to display the two-letter country code as text. The full names of the countries should only appear, when the user opens the dropdown. Something like:

+=======+===+
| DE    | v |
+=======+===+
| Germany   |
| England   |
| France    |
| Spain     |
| USA       |
+-----------+

Right now, my HTML code looks like this:

<select class="form-control w-25" data-bind="
    value: customAddress.country,
    options: countryList,
    optionsText: 'name',
    optionsValue: 'code',
    optionsCaption: 'Country'
" required></select>

Obviously, the dropdown displays "Germany" right now, if you select it. I found some ideas to replace the display text of the dropdown using jQuery in the onBlur event. But I fear, that this will interfere with the data binding mechanism of knockout (all properties are observables).

How can I solve that? Do I need a custom binding?


回答1:


You don't necessarily need a custom binding handler (and certainly don't need to resort to jQuery); this could be accomplished using the default binding handlers.

  1. Store the select menu state (open/closed) in a variable;
  2. Toggle this variable on the blur/focus events using the event binding. If it's a focus event, we assume the menu is open; if it's a blur event, we assume menu is closed.
  3. Pass a function to optionsText that will return either the code or the country, depending on the value of said variable.

JS:

function ViewModel() {
  var vm = this;

  vm.countries = [{
      code: 'DE',
      country: 'Germany'
    },
    {
      code: 'NL',
      country: 'The Netherlands'
    },
    {
      code: 'BE',
      country: 'Belgium'
    }
  ];

  vm.countrySelectIsOpen = ko.observable(false);
  vm.selectedCountry = ko.observable();

  vm.getOptionsText = function(item) {
    return item[vm.countrySelectIsOpen() ? 'country' : 'code'];
  }

  vm.toggleCountrySelectStatus = function(data, event) {
    vm.countrySelectIsOpen(event.type === 'focus');
  }
}

ko.applyBindings(new ViewModel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select class="form-control" data-bind="
        options: countries,
        optionsText: getOptionsText,
        optionsValue: 'code',
        optionsCaption: 'Country',
        value: selectedCountry,
        event: {
            blur: toggleCountrySelectStatus,
            focus: toggleCountrySelectStatus
        }
    "></select>

Fiddle: https://jsfiddle.net/thebluenile/hf70kg84/



来源:https://stackoverflow.com/questions/58765367/show-value-instead-of-text-in-knockout-bound-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!