Created
December 12, 2017 14:25
-
-
Save milannankov/4b53d64ef7798f5b45a378929d4dc900 to your computer and use it in GitHub Desktop.
Add New Item to Kendo MultiSelect on Enter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is possible implement this way using mvvm?