KnockOut JS - Dropdown to display values based on selection

427 views
Skip to first unread message

Konquest

unread,
Aug 8, 2020, 5:15:51 AM8/8/20
to KnockoutJS
Hi,

I am working on KnockOut JS and I need a dropdown to be selecting the values to display content based on the selection.

Lets say I have two values in the drop down Country and State.

How can I display the Country - USA/France/Germany when Country is selected.
and State - Texas/Kansas/New York when State is selected.

I want to develop it in KnockOut JS.

Thanks a lot.

SLG

unread,
Oct 19, 2020, 10:43:03 AM10/19/20
to KnockoutJS
There are multiple ways to do it

One way is to have the child dropdown depends on the parent selected value.

function ViewModel(){
  
   var self=this;

   self.countries=[];
   self.selectedCountry=ko.observable();
   

 //In case you needs to use ajax to load values from remote
//The build in options binding doesn't support dynamic data source, you have to use a flag to trigger the DOM to create a new option binding
  self._isStateLoading=ko.observable(); 
  self.selectedState=ko.observable();
 self.states=ko.compute(function(){
        self._isStateLoading(true);
         
        //You code to load states based on selected country, either via ajax or from a local array

       self._isStateLoading(false);
})




}


HTML

<div>
     <select data-binds="options:countries,value:selectedCountry"></select>
    <!-- ko if:_isStateLoading-->
     <span>  Loading...   </span>
   <!--/ko-->
    <!-- ko ifnot:_isStateLoading-->
     <select data-binds=" states  ,value:selectedState"></select>  
   <!--/ko-->
<div>
Reply all
Reply to author
Forward
0 new messages