Skip to content

Instantly share code, notes, and snippets.

@milannankov
Created December 12, 2017 14:25
Show Gist options
  • Save milannankov/4b53d64ef7798f5b45a378929d4dc900 to your computer and use it in GitHub Desktop.
Save milannankov/4b53d64ef7798f5b45a378929d4dc900 to your computer and use it in GitHub Desktop.
Add New Item to Kendo MultiSelect on Enter
<div id="example">
<div>
<h4>Choose products</h4>
<select id="products" style="width: 100%;"></select>
</div>
<script>
$(document).ready(function () {
widget = $("#products").kendoMultiSelect({
filter: "contains",
dataTextField: "ProductName",
dataValueField: "ProductID",
dataSource: dataSource,
}).data('kendoMultiSelect');
// listen for key presses on the MultiSelect input
widget.input.on('keydown', onInputKeyPress);
});
var widget = null;
var nextId = 2;
var dataSource = new kendo.data.DataSource({
data: [
{
"ProductID": 0,
"ProductName": "Paint brush"
},
{
"ProductID": 1,
"ProductName": "Plotter paper"
}
],
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { type: "number" },
ProductName: { type: "string" }
}
}
}
});
function onInputKeyPress(e) {
if (e.key !== "Enter") {
return;
}
selectValue(widget.input.val());
}
function selectValue(value) {
var id = addProductToSource(value);
addToSelectedValues(id);
}
function addProductToSource(productName) {
if (productName == "") {
return;
}
var newItem = {
"ProductID": nextId++,
"ProductName": productName
};
dataSource.add(newItem);
return newItem.ProductID;
}
function addToSelectedValues(productId) {
var existingProduct = dataSource.data().find(function (element) {
return element.ProductID === productId;
});
if (existingProduct) {
// Add to selected values
widget.value(widget.value().concat([existingProduct.ProductID]));
}
}
</script>
</div>
@IgnacioCastro0713
Copy link

Is possible implement this way using mvvm?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment