kendo-uikendo-mvvm

Prevent the delete key from working on Kendo ListBox


I'm using Kendo on Razor pages using MVVM. On a particular page I have a pair of ListBoxes. I want to stop users from deleting items from the boxes with the delete key.

If I trap and prevent the remove event from working, that solves the problem, except you can't then use the toolbox or drag and drop to transfer items from one box to the other (edit: because move is a combination of change & remove events).

This is how I was stopping the remove event...

<select style="min-width: 600px" id="listboxImports" data-role="listbox"
    data-text-field="title"
    data-value-field="id"
    data-selectable="multiple"
    data-toolbar='{tools: ["transferTo", "transferFrom"]}'
    data-connect-with="listboxSelected"
    data-draggable="true"
    data-template="template"
    data-drop-sources="['listboxSelected']"
    data-bind="source: imports, events: {remove: viewmodel.events.remove}"></select>

<script>
    var viewmodel = new kendo.observable({
        events: {
            remove: function(e) {
                e.preventDefault();
            },
            //
        }
    });
<script/>

I've also tried to trap the delete key's keydown event, but I cannot identify which of the many elements rendered when the ListBox is rendered is actually handling the event.

Can anyone tell me how I can have my cake and eat it please?


Solution

  • Took ma a while, inspired by the same question for kendo's Multiselect: https://docs.telerik.com/kendo-ui/controls/editors/multiselect/how-to/selection/prevent-removing-selected-items-on-backspace:

      $("#listBoxA").parent().get(0).addEventListener('keydown',  function(e) {
       if (e.keyCode == kendo.keys.DELETE) {
            e.stopImmediatePropagation();  
            e.preventDefault();
          }
     }, true)
    

    Full dojo: https://dojo.telerik.com/aFaCIkez/3

    The _keyDown handler is attached to the <ul> element. My solution attaches a new handler to its parent, using event capturing, so that handler will be executed before Kendo's, and thus stopping the event's propagation if the pressed key was delete.

    Alternatively, a possible workaround is to set navigatable to false, but you obviously lose all keyboard functionality. Example: https://dojo.telerik.com/IHICAziR