Set MultiSelects to Behave as TagBoxes
Environment
Product | Progress® Kendo UI® MultiSelect for jQuery |
Description
I want to enable the MultiSelect to:
- Accept custom text.
- Display the custom text as a tag by automatically adding the free text entry to its DataSource.
- Not open its drop-down.
How can I configure and customize the MultiSelect to behave as a TagBox?
Solution
Attach a handler for the
keyup
event ofEnter
to theinput
element of the MultiSelect. As a result, the handler adds the new text to the DataSource and selects the newly created entry.Use a CSS rule to force the pop-up to always remain hidden.
<style>
#products-list {
display: none !important;
}
</style>
<select id="products" style="width: 100%;"></select>
<script>
$(document).ready(function() {
var currentId = 1;
function onDataBound(e) {
$('.k-multiselect .k-input-inner').unbind('keyup');
$('.k-multiselect .k-input-inner').on('keyup', onClickEnter);
}
function onClickEnter(e) {
if (e.keyCode === 13) {
var widget = $('#products').getKendoMultiSelect();
var dataSource = widget.dataSource;
var input = $('.k-multiselect .k-input-inner');
var value = input.val().trim();
if (!value || value.length === 0) {
return;
}
var newItem = {
ProductID: currentId ++,
ProductName: value
};
dataSource.add(newItem);
var newValue = newItem.ProductID;
widget.value(widget.value().concat([newValue]));
}
}
$("#products").kendoMultiSelect({
dataTextField: "ProductName",
dataValueField: "ProductID",
dataSource: {
data: []
},
dataBound: onDataBound
});
});
</script>