Generic: interdependent selectors

populate selector dependent on choice of other selector

by KooiInc MeHere

HTML

<div class="txt">Filter contintent (sorted)</div>
<select id="continents">
 <option value = 0>All</option>   
 <option value = 1>Asia</option>
 <option value = 2>Europe</option>
 <option value = 3>Africa</option>
</select> 
<select id="selectcountries"></select>

<br>

<div class="txt">Filter odd/even (sorted)</div>
<select id="oddeven">
 <option value = 0>All</option>   
 <option value = 1>Odd</option>
 <option value = 2>Even</option>
</select>
<select id="numbers"></select> 

<br>
    
<div class="txt">Filter Male/Female (unsorted)</div>
<select id="malefemale">
 <option value = 0>All</option>   
 <option value = 1>Male</option>
 <option value = 2>Female</option>
</select> 
<select id="names"></select>

CSS

body {font: normal 0.8em verdana,arial}
.txt {width: 200px; display:inline-block}

JavaScript

/*
 -------------------------------------------------------
 syntax 
 MAIN.createRelatedSelector(
    from   -> the filtering element           
    to     -> the element for filtered options
    obj    -> An object containing the options per
              option of the filtering (from) element
    [sort] -> optional sorting method for sorting
              of the complete or filtered options list
 --------------------------------------------------------
*/

//create the interdepent selectors
function initSelectors(){
 // next 2 statements should generate error message, see console
 MAIN.createRelatedSelector(); 
 MAIN.createRelatedSelector(document.querySelector('#continents') );
 
 //countries
 MAIN.createRelatedSelector
     ( document.querySelector('#continents')           // from select element
      ,document.querySelector('#selectcountries')      // to select element
      ,{                                               // values object 
        Asia: ['China','Japan','North Korea','South Korea','India','Malaysia','Uzbekistan'],
        Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
        Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
      }
      ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
 );

 //numbers
 MAIN.createRelatedSelector
   (   document.querySelector('#oddeven')
      ,document.querySelector('#numbers')
      ,{
        Odd: [1,3,5,7,9,11,13,15,17],
        Even: [14,2,4,6,8,10,12,16],
       }
      ,function(a,b){ return +a - +b; }
 );

 // persons
 MAIN.createRelatedSelector
  (    document.querySelector('#malefemale')
      ,document.querySelector('#names')
      ,{
        Female: ['Mary','Jeanette','Jo','Anne'],
        Male: ['John','Charles','Edward','Jim'],
       }
 );
}

//create MAIN namespace
(function(ns){ // don't pollute the global namespace
    
 function create(from, to, obj, srt){
  if (!from) {
         throw CreationError('create: parameter selector...