如何创建依赖表单输入文本动态填充选项的联动下拉列表
实现方案
分为两种常用场景,可根据你的数据量选择:
场景1:数据量小于1000条,前端全量加载实现(无后端请求)
直接把所有baymatrix数据预存在前端JS中,输入时本地筛选,响应速度最快。
前端代码示例
<!-- 页面结构 --> <input type="text" id="searchInput" placeholder="输入描述关键词"> <select id="locationSelect"></select>
// 预存baymatrix全量数据 const baymatrix = [ { Location: "UW-01-03-04-XX", Description: "Yamaha Secondary Clutch" }, { Location: "UW-01-03-03-XX", Description: "Polaris Secondary Clutch" }, { Location: "UW-01-03-02-XX", Description: "Arctic Cat Secondary Clutch" }, { Location: "UW-01-03-01-XX", Description: "Bombardier Secondary Clutch" } ] const searchInput = document.getElementById('searchInput') const locationSelect = document.getElementById('locationSelect') // 绑定输入事件 searchInput.addEventListener('input', function() { // 统一转小写实现大小写不敏感匹配 const keyword = this.value.trim().toLowerCase() // 筛选匹配条目 const matchedList = baymatrix.filter(item => item.Description.toLowerCase().includes(keyword) ) // 清空原有下拉选项 locationSelect.innerHTML = '' // 插入新匹配选项 matchedList.forEach(item => { const option = document.createElement('option') option.value = item.Location option.textContent = item.Location locationSelect.appendChild(option) }) })
场景2:数据量大,走后端接口查询
避免前端加载过多数据,通过后端查询返回匹配结果。
后端查询SQL示例(MySQL为例)
SELECT Location FROM baymatrix WHERE LOWER(Description) LIKE CONCAT('%', LOWER(?), '%');
?为传入的用户搜索关键词,用LOWER函数统一转小写实现大小写不敏感匹配。
前端请求代码示例(带防抖优化)
const searchInput = document.getElementById('searchInput') const locationSelect = document.getElementById('locationSelect') // 防抖函数:避免用户输入时频繁发请求,延迟300ms执行 function debounce(func, delay = 300) { let timer return function(...args) { clearTimeout(timer) timer = setTimeout(() => func.apply(this, args), delay) } } // 绑定防抖的输入事件 searchInput.addEventListener('input', debounce(async function() { const keyword = this.value.trim() // 调用后端接口 const res = await fetch('/api/searchLocation', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ keyword: keyword }) }) const matchedList = await res.json() // 渲染下拉选项 locationSelect.innerHTML = '' matchedList.forEach(item => { const option = document.createElement('option') option.value = item.Location option.textContent = item.Location locationSelect.appendChild(option) }) }))
内容的提问来源于stack exchange,提问作者Mark Stevens
相关产品推荐
相关产品推荐

