问题
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.
- Store the select menu state (open/closed) in a variable;
- Toggle this variable on the blur/focus events using the
event
binding. If it's afocus
event, we assume the menu is open; if it's ablur
event, we assume menu is closed. - 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