[英]Set default selected value in Select2 fetching data from ajax
我使用一些输入字段和以下内容过滤结果列表:
$("#idCustomer").select2({
allowClear: true,
placeholder: "Filter",
ajax: {
url: 'ajax/search_customers.php',
dataType: 'json',
type: "GET",
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.Name,
id: item.ID
}
})
};
}
}
});
效果很好,但是提交表单后,我想用已经应用的过滤器填充输入。 可以接受其他所有输入:
例如:
<input id="minRange" name="minRange" value="<?php echo $minRange; ?>">
我的page.php
if ( isset($_POST) ) {
$minRange = $_POST['minRange'];
$idCustomer = $_POST['idCustomer'];
...
}
但是我不知道如何用我使用的搜索自动填充Select2。 例如,如果我写“ DEM”,我的Select2建议我“ DEMO CUSTOMER”(ID = 4)。 我选择它,提交表单,然后在重新加载页面后,Select2 idCustomer
仍然为空。 我想使用传递给表单进行搜索的id = 4将其初始化。
我试图追加$("#idCustomer").val(<?php echo $idCustomer; ?>).trigger("change");
但这不起作用。
我正在使用最新的4.1版本的插件
您必须提及选择自动完成功能
// HTML
// JS
$("#idCustomer").select2({
allowClear: true,
placeholder: "Filter",
ajax: {
url: 'ajax/search_customers.php',
dataType: 'json',
type: "GET",
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.Name,
id: item.ID
}
})
};
}
},
minLength: 2,
select: function(event, ui) {
var Name = ui.item.Name;
$("#minRange").val(Name);
}
})
;
解决:
<select id="idCustomer" name="idCustomer" class="form-control">
<?php if ( $idCustomer != "" ) { ?><option value="<?php echo $idCustomer; ?>"><?php echo get_info_by_id($idCustomer)['Name']; ?></option><?php } ?>
</select>
Select2完成其余工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.