I'm trying to get a drop-down list field to show or hide a certain div element based on the selected displayed text of the drop-down and not its value. I have a simple example below that shows it works when you set the data-bind
to value
:
<DIV data-bind="visible: chosenCountry() === 'GBR'">
<SELECT id="countryList" data-bind="value: chosenCountry">
But the drop-down field becomes an empty list when you set it to text
:
<DIV data-bind="visible: chosenCountry() === 'United Kingdom'">
<SELECT id="countryList" data-bind="text: chosenCountry">
Below is my complete example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<DIV data-bind="visible: chosenCountry() === 'GBR'">
You will see this message only when the chosen country is the United Kingdom.
</DIV><SELECT id="countryList" data-bind="value: chosenCountry">
<OPTION value="AUS">
Australia
</OPTION>
<OPTION value="BHS">
Bahamas
</OPTION>
<OPTION value="GBR">
United Kingdom
</OPTION>
</SELECT>
<SCRIPT src="knockout-3.3.0.js" type="text/javascript">
</SCRIPT>
<SCRIPT type="text/javascript">
var viewModel = {
chosenCountry: ko.observable("GBR")
};
ko.applyBindings(viewModel);
</SCRIPT>
</BODY>
</HTML>
A custom binding that tracks when the value of the select changes and pulls its text component will work for you:
This ensures that the text variable is tightly coupled to the value variable, which setting a change event handler doesn't do. My fiddle programmatically changes the value variable. Using
selectedTextA
as the binding handler causes the expected update, whileselectedTextB
does not.http://jsfiddle.net/f1bdr00s/