我目前正在使用Jquery Chosen插件:https://harvesthq.github.io/chosen/
太好了,但是我遇到了一个异常的问题,我一直在努力寻找答案!
我的情况如下:
我可以执行步骤1-3,没有任何问题。在步骤4上引入了问题。当我从数据库返回值并将数据绑定到字段时,如果数组中只有1个值,则该字段将显示两次。如果数组中的值超过1,则它将正常显示这些值。下面的图片使其更加清晰! :)
我的代码如下。问题在function fnsuccesscallback(data) {
部分中,我在其中有几个console.log项目可以检查我循环了多少次。
我尝试在每次函数调用开始时将selected-select的值重置为空,但这没有帮助:
newArray = [];
$(".chosen-select").chosen({ width: '100%' });
$('.chosen-select').val(newArray).trigger('chosen:updated');
这是我的代码减去从C#中提取的数据
$(document).ready(function () {
var array = [];
console.log(array);
getList();
function getList() {
//check if the incidentID is set to null, and don't make this call if it is as this is page load or please select.
var incidentID = $('input[id$=IDIncident]').val();
//if incidentID isn't undefined
if(!!incidentID){
console.log(incidentID.val)
var data = JSON.stringify({
obj: {
id: incidentID
}
});
$.ajax({
type: "POST",
url: "update.aspx/getSelectedServices",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnsuccesscallback,
error: fnerrorcallback
});
function btnclick() {
}
function fnsuccesscallback(data) {
//Convert the array to a string
var servicesString = JSON.stringify(data.d);
//strip the excess characters around the array
servicesString = servicesString.replace('\\\"]"', '');
servicesString = servicesString.replace('"[\\\"', '');
//Split the string into an array
//empty the array
array = [];
array.length = 0;
array = servicesString.split(',');
console.log(array);
//Array is currently empty - so setting it to empty
newArray = [];
$(".chosen-select").chosen({ width: '100%' });
$('.chosen-select').val(newArray).trigger('chosen:updated');
for (i = 0; i < array.length; i++) {
console.log("in loop");
console.log(i);
newArray[i] = $.trim(array[i]);
}
$('.chosen-select').val(newArray).trigger('chosen:updated');
}
function fnerrorcallback(result) {
alert(result.statusText);
console.log(result);
}
}
};
)};
<asp:ListBox ID="impactedServicesData" runat="server" AppendDataBoundItems="true" class="form-control incidentSelection impactedServicesData impactedServicesClass chosen-select" tabindex="8" multiple="">
</asp:ListBox>