我创建了一个网站来分享一些古老的家庭信件。我使用了两个Select2控件,让人们过滤谁写的信和谁收到的信件。所有这些都运行得很好,但我希望每个select2都能根据另一个中选择的内容进行过滤。也就是说,如果用户选择了一个特定的写信者,那么我希望收件人的select2只显示写信者写给的人。实际上,我已经完成了这个部分的工作,但是更新下拉列表的内容会删除它所拥有的任何选择,而且我无法更新这些选择。
一些笔记,然后我将展示一些代码,并试图澄清我看到和尝试什么。
两个selection.
两个select2下拉列表的HTML非常相似。下面是"From“下拉列表的代码:
<select id="from" class="js-example-basic-multiple" multiple="multiple" style="width: 100%">
<?php
echo GetPeople('F');
?>
</select>GetPeople是一个PHP函数,它调用数据库,然后将返回的数据转换为一系列行。该参数指示是获取"From“数据还是" to”数据。该参数还用作每个项的ID的一部分(因为事实证明,如果相同ID的选项出现在不同的select2控件中,则情况会迅速下降)。
function GetPeople ($type) {
$people = getdata("GetPeople", "'$type',''", "Couldn't retrieve list of people.<br/>");
$return = '';
while ($obj = mysqli_fetch_object($people)) {
$return .= "<option value='" . $obj->FullName . "' id='" . $type . $obj->iid . "'>" . $obj->FullName . "</option>";
}
return $return;
}每个OnChange控件的select2事件调用一个名为updatePeople的JS函数,传递'F‘或'T’来指示哪个select2需要更新其内容。也就是说,从下拉传递'T‘和从下拉传递'F’。
updatePeople使用AJAX来收集数据,构建一组新的行并将它们细分到指定的控件中。一切都如期而至。但是这样做会使该控件没有选择任何项。当我试图恢复更新之前控件的选择时,什么都不会发生。下面是updatePeople的代码,包括我恢复所选内容的尝试:
function updatePeople(cwhich) {
var results = '';
var success = false;
//get the currently selected list for the other dropdown, too
//so we can use them to restore selections later
if (cwhich == "F") {
var chosen = getChoices('#to');
var selecteditems = getChoices('#from',true);
} else {
var chosen = getChoices('#from');
var selecteditems = getChoices('#to',true);
}
var filters = cwhich + "','" + chosen + "'";
var fnargs = "GetPeople|'" + filters;
$.ajax({
url: 'retrievedata.php',
type: "POST",
async: false,
data: {"functionname": "getpeople", "arguments": fnargs},
dataType: "JSON",
success: function (obj) {
if (cwhich=="F") {
var target = "#from";
} else {
var target = "#to";
}
if ((obj===null)) {
//clear dropdown
$(target).html('');
}
else {
//build the list of options
var options = '';
for (line = 0; line < obj.length; line++) {
options += "<option value='" + obj[line].FullName + "' id='" + cwhich + obj[line].iid + "'>" + obj[line].FullName + "</option>";
}
window.allowupdate = false;
$(target).html(options);
//turn list of selected items into array
var arrSelected = selecteditems.split(',');
$(target).val(arrSelected);
$(target).trigger('change');
window.allowupdate = true;
}
success = true;
},
error: function (textStatus, errorThrown) {
success = false;
$("#testresult").text('Error occurred: '.textStatus);
console.log('Error occurred: '.textStatus);
}
});
}window.allowupdate位是因为试图更改一个下拉列表的选择会触发它的OnChange,而这将改变第一个下拉列表。因此,我在OnChange代码中添加了一个签入的标志,这样我就可以在不更改另一个的情况下更改其中一个。
我要寻找的是如何将修改后的select2控件设置为与更新控件内容之前相同的项。提亚
发布于 2022-01-05 21:10:48
解决了自己的问题。有两个问题:
$(target).select2('destroy');
$(target).html(options);
$(target).select2({placeholder: 'Anyone (or choose senders)'});https://stackoverflow.com/questions/70570952
复制相似问题