我正在拨打AJAX,返回的响应如下:
[{
Value: "val1",
Text: "text1"
}, {
Value: "val2",
Text: "text2"
}, {
Value: "val3",
Text: "text3"
}, {
Value: "val4",
Text: "text4"
}]
我尝试使用此答案中所述的方法添加它:Adding items to a Kendo multiSelect
我将代码修改为以下内容:
var multiSelect = $("#mySelect").data("kendoMultiSelect");
// Read original data content
var multiData = multiSelect.dataSource.data();
for (var i = 0; i < response.length; i++) {
// insert new element into copy of multiselect data
multiData.push({
text: response[i].Text,
value: response[i].Value
})
}
// Write back the modified data
multiSelect.dataSource.data(multiData);
但是,以此方式添加的所有新选项均显示为undefined
。我已经console.log
要response
来验证其中是否有数据。
我也无法在multiselect API中找到任何内容,例如clear()
或removeAll
。只是一个remove
,要求您在删除之前先获取每个dataItem
。我想念一个更好的方法吗?
答案 0 :(得分:2)
要清除选项,请使用
multiSelect.dataSource.data([]);
选中下面的演示。
$(document).ready(function() {
// create MultiSelect from select HTML element
var required = $("#required").kendoMultiSelect().data("kendoMultiSelect");
$("#btn").click(function() {
var multiSelect = $("#required").data("kendoMultiSelect");
var response = [ { Text: "ship 1", Value: "Value1" },{ Text: "ship 2", Value: "Value2" }, { Text: "ship 3", Value: "Value3" }, { Text: "ship 4", Value: "Value4" } ];
// clear previous data
multiSelect.dataSource.data([]);
var multiData = []; //multiSelect.dataSource.data();
for (var i = 0; i < response.length; i++) {
// insert new element into copy of multiselect data
multiData.push({
text: response[i].Text,
value: response[i].Value
})
}
// Write back the modified data
multiSelect.dataSource.data(multiData);
});
});
.demo-section label {
display: block;
margin: 15px 0 5px 0;
}
#get {
float: right;
margin: 25px auto 0;
}
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/multiselect/index">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.620/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2018.2.620/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.2.620/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example" role="application">
<div class="demo-section k-content">
<h4>Kendo - Multiselect - Append to dataSource</h2>
<label for="required">Required</label>
<select id="required" multiple="multiple" data-placeholder="Select attendees...">
<option>ABC</option>
<option>XYZ</option>
<option>PQR</option>
</select>
<button class="k-button" id="btn">GET Ajax data</button>
</div>
</div>
</body>
</html>