You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取HTML多选列表选中值并以逗号分隔显示在文本框中

多选下拉框选中值逗号拼接展示实现方法

具体实现步骤

  • 首先在现有Access Locations多选下拉框下方,新增一个只读文本输入框,用于展示拼接后的选中结果,避免用户手动篡改内容:
<br/>
<label>已选访问位置</label>
<input type="text" name="selected_locations" id="selected_locations" class="form-control" readonly />
  • 添加jQuery事件监听逻辑(Bootstrap框架默认已加载jQuery,无需额外引入依赖),监听多选框的选中状态变化,每次变化时遍历所有选中项,提取显示文本后用逗号拼接,赋值给上述文本框:
// 原生多选框使用该监听事件
$('select[name="select2[]"]').on('change', function() {
  const selectedList = [];
  // 遍历所有选中的option
  $(this).find('option:selected').each(function() {
    selectedList.push($(this).text().trim());
  });
  // 拼接后赋值给展示文本框
  $('#selected_locations').val(selectedList.join(','));
});

// 如果你使用了Select2插件渲染多选下拉框,请替换为以下监听事件
/*
$('select[name="select2[]"]').on('select2:select select2:unselect', function() {
  const selectedList = [];
  $(this).find('option:selected').each(function() {
    selectedList.push($(this).text().trim());
  });
  $('#selected_locations').val(selectedList.join(','));
});
*/

效果说明

完成上述配置后,用户每选中/取消选中一个下拉选项,下方文本框都会实时更新:选中Place 1、Place 2时,文本框会自动显示Place 1,Place 2,完全匹配需求。

内容的提问来源于stack exchange,提问作者Codec737

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 16:03:34