繁体   English   中英

jQuery 选择:如何从多个选择中获取所选选项文本的数组

[英]jQuery Chosen : How to get array of selected options text from a multiple select

我正在使用jQuery Chosen ,我需要将每个选项文本从多个选择的下拉列表中放入一个数组中。

我可以通过以下方式轻松获取数组中的所有值:

    <select id="select_custom" data-placeholder="Choose a city" style="width:50%;" class="chosen-processed" multiple>
      <option value="cty01">New York</option>
      <option value="cty02">Madrid</option>
      <option value="cty03">Montreal</option>
      <option value="cty04">Paris</option>
      <option value="cty05">Berlin</option>
    </select>

   var select_custom = jQuery("#select_custom");

   select_custom.change(function(){
    var values = select_custom.chosen().val();
   });

根据选择的选项,它将返回一个如下所示的数组:

    ['cty01', 'cty03', 'cty04']

获取文本而不是值的等效项是什么?

    ['New York', 'Montreal', 'Paris']

在此先感谢您的帮助!

var select_custom = jQuery("#select_custom");

select_custom.change(function(){
  var values = select_custom.chosen().val();

  var labels = [];

  for (var i = 0; i < values.length; i++) {
    var label = select_custom.find('[option value="'+values[i]+'"]').text();
    labels.push(label);
  }

  console.log(labels);

});

我们基本上是遍历每个值,在<select>字段中搜索与该值匹配的<option>标签,然后将其推送到labels数组。

您可以使用地图功能

https://api.jquery.com/jquery.map/

 $("#select_custom").change(function() { var text = $(this).find('option:selected').toArray().map(item => item.text).join(); console.clear(); console.log(text); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="select_custom" data-placeholder="Choose a city" style="width:50%;" class="chosen-processed" multiple> <option value="cty01">New York</option> <option value="cty02">Madrid</option> <option value="cty03">Montreal</option> <option value="cty04">Paris</option> <option value="cty05">Berlin</option> </select>

 var select_custom = jQuery("#select_custom"); var arr = []; select_custom.change(function(){ var text = $('#select_custom option:selected').text(); if(!arr.includes(text)) { arr.push(text); } console.log(arr); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="select_custom" data-placeholder="Choose a city" style="width:50%;" class="chosen-processed" multiple> <option value="cty01">New York</option> <option value="cty02">Madrid</option> <option value="cty03">Montreal</option> <option value="cty04">Paris</option> <option value="cty05">Berlin</option> </select>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM