neo
neo

Reputation: 2471

Knockout checked binding based on drop down selection

Say I have following binding:

<p>blah blah<input type="checkbox" data-bind="checked: shouldShow" /></p>
 <div data-bind="visible: shouldShow ">...</div>    
 <select data-bind="options: availableCountries,
                       optionsText: 'countryName',
                       value: selectedCountry,
                       optionsCaption: 'Choose...'">
 </select>

What I want to do is:

  1. when a certain country is selected, the checkbox should be automatically checked, and the div section should show.
  2. When a user select a different country, the checkbox is not automatically selected, but if the user manually check the checkbox, the div should show.

I have the following

 shouldShow = ko.computed(function() {                
                if(selectedCountry == 'UK') 
                    return true;
                else
                    return false;
             }, this);

Now this works for 1, but if the user select a different country, and when the user select the checkbox, nothing happened. How do i solve that?

Upvotes: 0

Views: 73

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

A manual subscription might work well for this scenario, if I understand the requirements correctly.

You can make shouldShow an observable, then create a manual subscription against selectedCountry to determine if you should update shouldShow. This allows shouldShow to maintain a value independently from the country.

this.shouldShow = ko.observable();

this.selectedCountry = ko.observable();

this.selectedCountry.subscribe(function(newValue) {
    this.shouldShow(newValue === "UK");
}, this);

When the country is changed, the checkbox will be updated. However, if a user checks the box, it will still set it to true.

Upvotes: 2

Related Questions