1、问题背景
select2搜索下拉框,当满足某种条件时,让它默认选中空值
2、问题原因
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>select2默认选择空值</title>
<link rel="stylesheet" href="../css/select2.css" />
<script src="../js/jquery-3.2.1.js"></script>
<script src="../js/select2.js"></script>
<script>
$(function(){
$("#selectNull").select2();
$("#selectNull").on("select2:select",function(){
var data = $(this).val();
if(data=="3")
{
$("#selectNull").val("");
}
});
});
</script>
</head>
<body>
<div>
<select id="selectNull" class="js-example-basic-single" style="400px;">
<option value=""></option>
<option value="1">AA</option>
<option value="2">BB</option>
<option value="3">CC</option>
<option value="4">DD</option>
<option value="5">EE</option>
<option value="6">FF</option>
</select>
</div>
</body>
</html>
如果直接利用$("#selectNull").val(""); 发现效果不佳;或者利用$("#selectNull").select2.select2.("val","");也不行
3、解决办法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>select2默认选择空值</title>
<link rel="stylesheet" href="../css/select2.css" />
<script src="../js/jquery-3.2.1.js"></script>
<script src="../js/select2.js"></script>
<script>
$(function(){
$("#selectNull").select2();
$("#selectNull").on("select2:select",function(){
var data = $(this).val();
if(data=="3")
{
$("#selectNull").val("").select2();
}
});
});
</script>
</head>
<body>
<div>
<select id="selectNull" class="js-example-basic-single" style="400px;">
<option value=""></option>
<option value="1">AA</option>
<option value="2">BB</option>
<option value="3">CC</option>
<option value="4">DD</option>
<option value="5">EE</option>
<option value="6">FF</option>
</select>
</div>
</body>
</html>
使用$("#selectNull").val("").select2(); 这样才有效