根据第一个选择过滤第二个选择(在数组中过滤)
首先,我发现很少有类似的帖子,但它们与这个并不完全相同。因为就我而言,我需要像 in_array 值一样进行过滤。
我有两个选择。首先,产品列表。二、供应商名录。一种产品可能有多个供应商。我将 html 中的 data-suppliers
中的供应商 ID 作为字符串传递。我如何使其数组并用作第二个选择选项列表中的过滤器。或者还有其他方法可以做到吗?
我的html:
<select id="products">
<option data-suppliers="1" value="apple">Apple</option>
<option data-suppliers="1,3" value="olive">Olive</option>
<option data-suppliers="1,2,5" value="lemon">Lemon</option>
<option data-suppliers="4,6" value="tea">Tea</option>
<select>
<select id="suppliers">
<option value="1">Firm-A</option>
<option value="2">Firm-B</option>
<option value="3">Firm-C</option>
<option value="4">Firm-D</option>
<option value="5">Firm-E</option>
<option value="6">Firm-F</option>
<select>
JS代码:
$('#suppliers').first().hide();
$("#products").change(function() {
if ($(this).data('options') === undefined) {
$(this).data('options', $('#suppliers option').clone());
$('#suppliers').first().show();
}
var ids = $(this).find(":selected").data('suppliers');
console.log(ids);
var options = $(this).data('options').filter('[value*=' + ids + ']');
$('#suppliers').html(options);
});
First of all, I found few similar posts, but they do not exactly same as this one. Because in my case i need to filter like in_array value.
I have 2 select options. First, Products list. Second, Suppliers List. One product might have multiply suppliers. I pass supplier ids in data-suppliers
in html as string. How can i make it array and use as filter in second select option list. Or any other ways to do it?
My html:
<select id="products">
<option data-suppliers="1" value="apple">Apple</option>
<option data-suppliers="1,3" value="olive">Olive</option>
<option data-suppliers="1,2,5" value="lemon">Lemon</option>
<option data-suppliers="4,6" value="tea">Tea</option>
<select>
<select id="suppliers">
<option value="1">Firm-A</option>
<option value="2">Firm-B</option>
<option value="3">Firm-C</option>
<option value="4">Firm-D</option>
<option value="5">Firm-E</option>
<option value="6">Firm-F</option>
<select>
JS Code:
$('#suppliers').first().hide();
$("#products").change(function() {
if ($(this).data('options') === undefined) {
$(this).data('options', $('#suppliers option').clone());
$('#suppliers').first().show();
}
var ids = $(this).find(":selected").data('suppliers');
console.log(ids);
var options = $(this).data('options').filter('[value*=' + ids + ']');
$('#suppliers').html(options);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试这样做:
首先,我隐藏
supplier
选择中的所有选项,然后过滤选项以获取与products
中的条件匹配的选项并显示这些选项。最后,我将supplier
值设置为第一个可见选项,否则您将看到默认的隐藏选项。演示
You can try do it like this:
First I hide all options in the
supplier
select, then I filter the options to get thoses that match the criteria fromproducts
and show those. At the end I set thesupplier
value to the first visible option, else you would see a hidden option as default.Demo