【问题标题】:Storing multiple selected options into a string将多个选定的选项存储到一个字符串中
【发布时间】:2023-01-29 23:02:40
【问题描述】:
 <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']};
var dict3 = {'A': ['Item1', 'Item2'],
          'B': ['Item3', 'Item4'],
          'C': ['Item5', 'Item6']
};
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>';
               $(".chosen-select").trigger("chosen:updated");
           });
  };
</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 id="selectNeigh" multiple class='chosen-select'"></select>
    </form>
</body>

我无法将所选选项存储到变量中。我以前使用简单的 HTML 多选并使用下面的代码来获取选定的选项:

const options = document.getElementById('selectNeigh').selectedOptions; 
const values = Array.from(options).map(({ value }) => "'" + value + "'"); 
const output = values.join();

但是,我不确定如何使用 jquery 实现相同的目的。我尝试使用以下实现:JQuery - Multiple Select Options 但没有成功

【问题讨论】:

  • 嗨,这个你检查this答案?
  • 嗨@Swati 我尝试执行以下操作: var result = $("#selectNeigh .chosen-select").val();然后我转成字符串,没有成功

标签: javascript html jquery


【解决方案1】:

您可以使用 jQuery val() 方法获取选择元素的选定选项。在这种情况下,您将在 ID 为 selectNeigh 的选择元素上使用它。

const selectedOptions = $("#selectNeigh").val();

这将为您提供所选选项值的数组。

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2021-04-07
    相关资源
    最近更新 更多