如何使用jQuery从两个下拉选择框中获取数组形式的选中值?
jQuery获取多下拉框选中值并过滤对象数组方案
问题场景
你是jQuery新手,需要从两个下拉框获取选中值组成数组,再用这个数组过滤对象数组。但当前代码只能获取第一个下拉框的值,第二个返回空,原始代码如下:
原始HTML代码
<div class="variant"> <select name="d001" id="attribute"> <option value="black">Black</option> <option value="pink">Pink</option> <option value="white">White</option> </select> <select name="d002" id="attribute"> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> </div>
原始JS代码
$(document).on('change','.variant select',function(a){ a.preventDefault(); var select = $(this).val(); var attribut = a.target.name; // 尝试获取两个选框的选中值,但只能拿到第一个,第二个为空 let selectedVal = $("option:selected").val(); console.log(selectedVal); })
解决步骤
1. 修正HTML的ID重复问题
HTML规范中ID必须唯一,重复ID会导致选择器异常,把两个select的id="attribute"改成class="attribute":
<div class="variant"> <select name="d001" class="attribute"> <option value="black">Black</option> <option value="pink">Pink</option> <option value="white">White</option> </select> <select name="d002" class="attribute"> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> </div>
2. 获取所有选中值组成数组
$("option:selected").val()只会返回第一个选中元素的值,要用.map()遍历所有选中项,再用.get()转成普通数组:
$(document).on('change','.variant select',function(){ // 收集所有下拉框的选中值,组成数组 let selectedValues = $('.variant select option:selected').map(function() { return $(this).val(); }).get(); console.log(selectedValues); // 输出示例:["black", "8"] })
3. 用选中数组过滤对象数组
假设你有如下对象数组(比如产品列表):
const products = [ { color: "black", size: "7", name: "黑款7码" }, { color: "pink", size: "8", name: "粉款8码" }, { color: "white", size: "9", name: "白款9码" }, { color: "black", size: "8", name: "黑款8码" } ];
在change事件中添加过滤逻辑,这里假设选中数组的第一个值对应color,第二个对应size:
$(document).on('change','.variant select',function(){ let selectedValues = $('.variant select option:selected').map(function() { return $(this).val(); }).get(); // 过滤对象数组 const filteredProducts = products.filter(product => { return product.color === selectedValues[0] && product.size === selectedValues[1]; }); console.log(filteredProducts); // 输出匹配的产品对象 })
如果需要更灵活的匹配(比如根据select的name对应对象属性),可以先收集属性名和值的映射:
$(document).on('change','.variant select',function(){ let selectedMap = {}; $('.variant select').each(function() { selectedMap[$(this).attr('name')] = $(this).val(); }); // 假设对象的属性名和select的name对应(比如d001对应color,d002对应size) const filteredProducts = products.filter(product => { return product.color === selectedMap.d001 && product.size === selectedMap.d002; }); console.log(filteredProducts); })
内容的提问来源于stack exchange,提问作者Chihiro Japan
相关产品推荐
相关产品推荐

