gpt4 book ai didi

javascript - 根据第一个值在第二个 Select2 下拉列表中显示选项

转载 作者:行者123 更新时间:2023-12-02 23:01:55 25 4
gpt4 key购买 nike

我想仅显示更改后基于第一个下拉值(父级)的第二个下拉列表(子级)属性数据值中的选项,并隐藏其余选项。

$('.custom_select').select2()

$('select[name=parent]').on('change', function(){
// show only options from child equals to this.val()
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
<select class="custom_select" name="parent">
<option value="1">example 1</option>
<option value="1">example 1</option>
<option value="2">example 2</option>
<option value="3">example 3</option>
</select>
<select class="custom_select" name="child">
<option data-value="1">child 1</option>
<option data-value="1">child 1</option>
<option data-value="2">child 2</option>
<option data-value="3">child 3</option>
</select>

最佳答案

您可以获取第一个选择框的值,然后根据隐藏或显示选项将其与第二个选择框的选项进行比较,即:

$('.custom_select').select2()

$('select[name=parent]').on('change', function() {
//getting value
var val = $(this).val();
//looping through options
$('select[name=child] option').each(function() {
var self = $(this);
if (self.attr("data-value") == val) {
//if the option have that values show option
$("select[name=child] option[data-value='" + val + "']").prop('disabled', false);

} else {
//other options which don't have selected value hide them
$("select[name=child] option:not(:contains('" + val + "'))").prop('disabled', true);

}
});
});
.select2-container--default .select2-results__option[aria-disabled=true] {
display: none;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
<select class="custom_select" name="parent">
<option value="1">example 1</option>
<option value="2">example 2</option>
<option value="3">example 3</option>
</select>
<select class="custom_select" name="child">
<option data-value="1">child 1</option>
<option data-value="2">child 2</option>
<option data-value="3">child 3</option>
</select>

关于javascript - 根据第一个值在第二个 Select2 下拉列表中显示选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745718/

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