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

如何实现带提交按钮的multiple select多选下拉框,提交多值调用API查询

解决方案

1. 调整HTML结构

去掉原有select的onchange触发逻辑,新增提交按钮,无需绑定form的onchange事件,避免每选一个选项就触发查询:

<select multiple id="selectButton"></select>
<button type="button" id="queryBtn">提交查询</button>

如果要保留form结构,需要阻止表单默认提交跳转行为,写法如下:

<form id="queryForm">
  <select multiple id="selectButton"></select>
  <input type="submit" value="提交查询" />
</form>

2. 逻辑实现(原生JS+D3版本)

移除原来的onchange绑定,改为监听提交按钮的点击事件,批量获取选中值后调用接口:

// 监听按钮点击事件
document.getElementById('queryBtn').addEventListener('click', function() {
  // 获取所有选中的选项值
  const selectEl = document.getElementById('selectButton');
  const selectedValues = Array.from(selectEl.selectedOptions).map(opt => opt.value);
  // 调用查询函数
  showProcessor(selectedValues);
})

// 调整showProcessor函数,适配多值传参
function showProcessor(valueArr) {
  // 方案1:后端接收逗号分隔的proc_name参数,直接拼接
  const paramStr = valueArr.map(v => encodeURIComponent(v)).join(',');
  d3.json(`http://localhost:3001/api/v2/monitoring/SANDBOX2/d3_ui_bar_metrics?proc_name=${paramStr}`)
  
  // 方案2:后端支持接收多个proc_name数组参数,按标准query格式拼接
  // const paramStr = valueArr.map(v => `proc_name=${encodeURIComponent(v)}`).join('&');
  // d3.json(`http://localhost:3001/api/v2/monitoring/SANDBOX2/d3_ui_bar_metrics?${paramStr}`)
}

如果用form结构的话,监听submit事件即可:

document.getElementById('queryForm').addEventListener('submit', function(e) {
  // 阻止表单默认跳转提交
  e.preventDefault();
  // 后续获取选中值、调用接口的逻辑和上面一致
  const selectEl = document.getElementById('selectButton');
  const selectedValues = Array.from(selectEl.selectedOptions).map(opt => opt.value);
  showProcessor(selectedValues);
})

3. 逻辑实现(jQuery简化版本)

如果使用jQuery,获取多选值的逻辑更简洁:

// 监听点击事件
$('#queryBtn').on('click', function() {
  // jQuery直接调用val()即可返回选中值的数组
  const selectedValues = $('#selectButton').val();
  showProcessor(selectedValues);
})

// showProcessor函数和上面保持一致即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:54:05