javascript 填充JQuery多选选项

vzgqcmou  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(328)
<script src="https://js.arcgis.com/4.25/"></script>
 <script src="https://cdn.jsdelivr.net/gh/harvesthq/chosen@gh-pages/docsupport/jquery-3.2.1.min.js"></script>
 <script src="https://cdn.jsdelivr.net/gh/harvesthq/chosen@gh-pages/chosen.jquery.min.js"></script>
 <link href="https://cdn.jsdelivr.net/gh/harvesthq/chosen@gh-pages/chosen.min.css" rel="stylesheet">
 <script>
 $(document).ready(function() {   
     $(".chosen-select").chosen({
         no_results_text: "Oops, nothing found!"
     })
 });
</script>
<script>

var dict1 = {'Canada': ['', 'Toronto'],'USA': ['', 'Hawaii']};
var dict2= {'Toronto': ['','A', 'B'],Hawaii': ['C', 'D']};
var dict3 = {'A': ['Item1', 'Item2'],
          'B': ['Item3', 'Item4'],
          'C': ['Item5', 'Item6'],
          'D': ['Item7', 'Item8']
};
var regionOption = document.querySelector("#municipality");
var districtOption = document.querySelector("#districtName");
var provOption = document.querySelector("#region");
var neighOption = document.querySelector("#selectNeigh");
     
createOption(provOption, Object.keys(regions));
     
provOption.addEventListener('change', function() {
     createOption(regionOption, dict1[provOption.value]);
});
regionOption.addEventListener('change', function() {
      createOption(districtOption, dict2[regionOption.value]);
});
districtOption.addEventListener('change', function() {
        createOption(neighOption, dict3[districtOption.value]);
 });
  function createOption(dropDown, options) {
      dropDown.innerHTML = '';
          options.forEach(function(value) {
               dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
           });
  };
</script>
 
<body>
    <select id="region" style="width: 125px;"></select>
    <select id="municipality" style="width: 125px;"></select>
    <select id="districtName" style="width: 125px;"></select>
    <form action="http://httpbin.org/post" method="post">
         <select data-placeholder='Select Neighbourhoods' id="selectNeigh" multiple class='chosen-select'style="width: 125px;"></select>
    </form>
</body>

因此,如果我使用常规的html多选,我当前的代码可以正常工作。但是,当我实现以下代码时:HTML: Select multiple as dropdown。选择八的选项不再填充。有人能帮我一下吗?

xzlaal3s

xzlaal3s1#

https://harvesthq.github.io/chosen/开始
如果你需要更新你的选择字段中的选项,并希望Chosen能够接受这些更改,你需要在该字段中触发"chosed:updated"事件,Chosen将根据更新的内容重新构建自己。
$("#form_field").trigger("chosen:updated");
因此,您已经在createOption函数中触发了update事件。

function createOption(dropDown, options) {
      dropDown.innerHTML = '';
          options.forEach(function(value) {
               dropDown.innerHTML += '<option name="' + value + '">' + value + '</option>';
           });
      
       $(".chosen-select").trigger("chosen:updated");
  };

相关问题