我使用的是jQuery Chosen,我需要将每个选项text放在多选下拉列表的数组中。
我可以很容易地获得数组中的所有值:
<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
数组。
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>
您可以使用映射函数
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);
$("#result").text(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>
<div id="result"></div>