如何用jQuery获取Select2多选下拉框选中项title属性并写入文本框
实现方案
Select2默认依赖jQuery,你可以直接用下面的代码实现需求:
// 提取所有选中项的title属性,用英文逗号拼接 const selectedTitles = $('.select2-selection__choice') .map(function() { return $(this).attr('title'); }) .get() .join(','); // 将拼接好的字符串赋值到目标文本框,把#target-input替换成你实际的文本框选择器即可 $('#target-input').val(selectedTitles);
如果需要在Select2选中项变动时自动同步内容,直接绑定change事件即可:
// 把#your-select2-element替换成你初始化Select2时绑定的原下拉框选择器 $('#your-select2-element').on('change', function() { const selectedTitles = $('.select2-selection__choice') .map(function() { return $(this).attr('title'); }) .get() .join(','); $('#target-input').val(selectedTitles); });
如果不想用jQuery,也可以用原生JS实现:
// 提取title并拼接 const selectedChoices = document.querySelectorAll('.select2-selection__choice'); const selectedTitles = Array.from(selectedChoices) .map(item => item.getAttribute('title')) .join(','); // 赋值到目标文本框 document.querySelector('#target-input').value = selectedTitles;
注意说明
.select2-selection__choice是Select2多选模式下固定的选中项类名,只会匹配已选中的选项,不会匹配到搜索输入框对应的li元素- 直接操作DOM的方式适配所有Select2 4.x版本,不需要额外处理Select2返回的数据源结构
内容的提问来源于stack exchange,提问作者user3124540
相关产品推荐
相关产品推荐

