根据之前选择的 JavaScript 和 html 下拉列表选项更改下拉列表信息

问题描述 投票:0回答:1

在我的网站上,我有两个下拉框,在框 1 中,用户将根据为他们提供的选项选择一个国家/地区,然后在第二个下拉框中,为他们提供的选项将是他们之前选择的国家/地区的城市。

我使用java脚本和html来创建它,但是它不起作用。第二个下拉框要么根本不会出现,要么即使出现,也会提供零个选项可供选择。

这是我的html代码(我相信这不是问题)

<div class="Location">
                <select id="location" class="dropbtn" name="location" style='display:none;' onchange='CheckLocation(this.Value);' required>
                    <option value="AL">Albania</option>
                    <option value="DZ">Algeria</option>
                    <option value="ZW">Zimbabwe</option>
                </select>
            </div>

            <div class="Location-City">
                <select id="city" class="dropbtn" name="city" style='display:none;' required>
                </select>
            </div>

然后这是我的 javascript 代码

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

//create MAIN namespace
(function(ns){ // don't pollute the global namespace
    
 function create(from, to, obj, srt){
  if (!from) {
         throw CreationError('create: parameter selector [from] missing');
  }
  if (!to) {
         throw CreationError('create: parameter related selector [to] missing');
  }
  if (!obj) {
         throw CreationError('create: related filter definition object [obj] missing');
  }
  
  //retrieve all options from obj and add it
  obj.all = (function(o){
     var a = [];
     for (var l in o) {
       a = /array/i.test (o[l].constructor) ? a.concat(o[l]) : a;
     }
     return a.sort(srt);
  }(obj));
 // initialize and populate to-selector with all
  populator.call( from
                  ,null
                  ,to
                  ,obj
                  ,srt
  );
    
  // assign handler    
  from.onchange = populator;

  function initStatics(fn,obj){
   for (var l in obj) {
       if (obj.hasOwnProperty(l)){
           fn[l] = obj[l];
       }
   }
   fn.initialized = true;
  }
     
 function populator(e, relatedto, obj, srt){
    // set pseudo statics
    var self = populator;
    if (!self.initialized) {
        initStatics(self,{optselects:obj,optselectsall:obj.all,relatedTo:relatedto,sorter:srt || false});
    }
     
    if (!self.relatedTo){
        throw 'not related to a selector';
    }
    // populate to-selector from filter/all
    var optsfilter = this.selectedIndex < 1
                   ? self.optselectsall 
                   : self.optselects[this.options[this.selectedIndex].firstChild.nodeValue]
       ,cselect = self.relatedTo
       ,opts = cselect.options;
    if (self.sorter) optsfilter.sort(self.sorter);
    opts.length = 0;
    for (var i=0;i<optsfilter.length;i+=1){
        opts[i] = new Option(optsfilter[i],i);
    }
  }
 }
    
 // custom Error
 function CreationError(mssg){
     return {name:'CreationError',message:mssg};
 }

 // return the create method with some error handling   
 window[ns] = { 
     createRelatedSelector: function(from,to,obj,srt) {
          try { 
              if (arguments.length<1) {
                 throw CreationError('no parameters');
              } 
              create.call(null,from,to,obj,srt); 
          } 
          catch(e) { console.log('createRelatedSelector ->',e.name,'\n'
                                   + e.message +
                                   '\ncheck parameters'); }
        }
 };    
}('MAIN'));
//initialize
initSelectors();

现在javascript代码基于这个jsfiddle https://jsfiddle.net/KooiInc/XH6vh/但它已经被修改以适应我的网站和html代码。

我从我的文件中删除了其他元素以检查它们没有干扰,所以这无疑是问题代码,但因为我不太了解java脚本,所以我不知道从哪里开始。

javascript html web-testing
1个回答
0
投票

要么我不明白你的要求,要么你把代码弄复杂了。这是我的方法。
->将国家和城市存储在键值对中
->动态地将选项添加到国家/地区下拉列表中。
->在国家/地区下拉列表中添加 onchange 事件,这将更改城市选择选项。

这是简单的代码。

<body>
    <select id="countries" onchange="handleChange()">   
        
    </select>
    <select id="cities">

    </select>
    <script>
        const countrySelector = document.getElementById('countries');
        const countries = {
            "Nepal": ['Kathmandu', 'Pokhara'],
            "Australia": ["Brisbane", "Adelaide", "Perth"],
            "Usa": ["Chicago", "Boston", "San Fransisco"],
        };
        Object.keys(countries).forEach(country => {
            const option = document.createElement('option');
            option.textContent = country;
            option.value = country;
            countrySelector.appendChild(option);
        });
        function handleChange(){
            var selectedCountry = document.getElementById("countries").value;
            const citySelector = document.getElementById('cities');
            var cities = countries[selectedCountry];

            //clear previous options
            citySelector.innerHTML = '';
            
            cities.forEach(city => {
                const option = document.createElement('option');
                option.textContent = city;
                option.value = city;
                citySelector.appendChild(option);
            })
        }
    </script>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.