我有两个下拉列表,第一个显示项目的编号,第二个显示项目名称,因此用户可以按项目编号或项目名称选择项目,如果他选择项目编号,另一个下拉列表将更新选定的值她是我的代码
我创建简单的更改功能以更新另一个下拉值
$('.select').select2({
"width":"100px"
});
$(document).on("change", "#block_name", function () {
id = $(this).val();
$("#block_number").select2('val',id);
});
$(document).on("change", "#block_number", function () {
id = $(this).val();
$("#block_name").select2('val',id);
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select name="block" id="block_name" class="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select name="block_number" id="block_number" class="select">
<option value="1">block1</option>
<option value="2">block2</option>
<option value="3">block3</option>
<option value="4">block4</option>
<option value="5">block5</option>
</select>
任何人都可以帮助我,我会很感激
答案 0 :(得分:2)
设置select2下拉列表的值会触发change事件,从而导致无限循环。所以你必须有一个案例。像这样:
$('.select').select2({
"width":"100px"
});
$(document).on("change", "#block_name", function () {
id = $(this).val();
if($("#block_number").val() != id){
$("#block_number").select2('val',id);
}
});
$(document).on("change", "#block_number", function () {
id = $(this).val();
if($("#block_name").val() != id){
$("#block_name").select2('val',id);
}
});
答案 1 :(得分:0)
像这样改变:
$(document).ready(function(){
$('.select').css({width:100});
$("#block_name").on("change", function () {
id = $(this).val();
$("#block_number option[value = " + id + "]").prop("selected",true);
})
$("#block_number").on("change", function () {
id = $(this).val();
$("#block_name option[value = " + id + "]").prop("selected",true);
})
})
最终代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select name="block" id="block_name" class="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select name="block_number" id="block_number" class="select">
<option value="1">block1</option>
<option value="2">block2</option>
<option value="3">block3</option>
<option value="4">block4</option>
<option value="5">block5</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.select').css({width:100});
$("#block_name").on("change", function () {
id = $(this).val();
$("#block_number option[value = " + id + "]").prop("selected",true);
})
$("#block_number").on("change", function () {
id = $(this).val();
$("#block_name option[value = " + id + "]").prop("selected",true);
})
})
</script>
</body>
</html>
&#13;