gpt4 book ai didi

javascript - 级联选择: Show different options when specific options is selected

转载 作者:行者123 更新时间:2023-12-02 15:41:44 25 4
gpt4 key购买 nike

当用户选择特定选项时,我需要显示一些选项。我想隐藏 name="products"中的一些选项,例如过滤器:

<select name="category">
<option value="fruit">fruits</option>
<option value="meal">meals</option>
<option value="drink">drinks</option>
</select>

<select name="products"><!--Always visible-->
<option default selected>select an option</option><!--when fruit is selected-->
<option id="fruit" value="apple">apple</option>
<option id="fruit" value="orange">orange</option><!--when meal is selected-->
<option id="meal" value="chicken">chicken</option>
<option id="meal" value="beef">beef</option><!--when drink is selected-->
<option id="drink" value="vodka">vodka</option>
<option id="drink" value="wishkey">wishkey</option>
</select>

我需要有关如何使用 javascript 或 Jquery 执行此操作的帮助。

最佳答案

我建议将第二个select中的id更改为class,因为id必须是唯一的,然后您可以捕获更改第一个 select 的事件 并仅显示与以下值匹配的选项:

<强> DEMO

更新了 html

<select name="category">
<option value="fruit">fruits</option>
<option value="meal">meals</option>
<option value="drink">drinks</option>
</select>
<select name="products">
<!--Always visible-->
<option selected>select an option</option>
<!--when fruit is selected-->
<option class="fruit" value="apple">apple</option>
<option class="fruit" value="orange">orange</option>
<!--when meal is selected-->
<option class="meal" value="chicken">chicken</option>
<option class="meal" value="beef">beef</option>
<!--when drink is selected-->
<option class="drink" value="vodka">vodka</option>
<option class="drink" value="wishkey">wishkey</option>
</select>

JS

$("select[name='category']").on('change',function(){
var value=$(this).val(); //get the selected value
$('select[name="products"]').find('option:not(:first)').hide(); //hide all options except first
$('select[name="products"]').find('option.'+value+'').show();//show only matching options
});

关于javascript - 级联选择: Show different options when specific options is selected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32515775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com