Disable up and down arrows for numeric edit with arrow-scrolling

Hi,

I have a grid with one editable numeric column. I want to be able to use the arrow buttons to navigate the grid. This is working, but the up and down arrows are still changing the numeric values. 


I have tried using preventDefault and event.cancel, but neither is working.


Grid code:

@Html.EJS().Grid("CurrentClaim").DataSource(ds => ds.Url(gridDataSource).BatchUrl(batchUpdateUrl).Adaptor("UrlAdaptor")).ActionBegin("actionBegin").ActionComplete("actionComplete").AllowSorting().ToolbarClick("toolbarClick").Created("created").Load("load").AllowExcelExport().Columns(col =>

                    {

                        col.Field("UniqueCode").HeaderText("Unique").Visible(false).Width("0").IsPrimaryKey(true).Add();

                        col.Field("ClaimId").HeaderText("ClaimId").Visible(false).Width("0").Add();

                        col.Field("ProductFamily").HeaderText("Family").Width("90").AllowEditing(false).Add();

                        col.Field("ProductCode").HeaderText("Product").Width("130").AllowEditing(false).Add();

                        col.Field("Quantity").HeaderText("Qty").Type("number").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("80").EditType("numericedit").Edit(new

                        {

                            @params = new Syncfusion.EJ2.Inputs.NumericTextBox()

                        {

                       // ValidateDecimalOnType = true,

                        Decimals = 0,

                        Max = 1000,

                        Min = 0,

                        Format = "N",

                        ShowSpinButton = false,

                        ShowClearButton = false}}).Add();

                        col.Field("PromoPeriodText").HeaderText("Promo Period").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Width("160").AllowEditing(false).Add();

                    }).AllowPaging().PageSettings(

                        page => { page.PageSizes((new string[] { "10", "20", "50", "All" })); page.PageSize(20); }).AllowFiltering().FilterSettings(Filter =>

                { Filter.Type(Syncfusion.EJ2.Grids.FilterType.Excel); }

                        ).Toolbar(toolbarItems).Width("660").EditSettings(edit => { edit.AllowAdding(false).AllowEditing(true).AllowDeleting(false).Mode(Syncfusion.EJ2.Grids.EditMode.Batch); }).Render()


Relevant javascript:

function created() {

    var grid = document.getElementById('CurrentClaim').ej2_instances[0];

    grid.getContentTable().addEventListener('click', function (args) {

        if (args.target.classList.contains('e-rowcell')) {

            grid.editModule.editCell(parseInt(args.target.getAttribute('index')),

                grid.getColumnByIndex(parseInt(args.target.getAttribute('data-colindex'))).field);

        }

    });

}


function load() {

    var grid = document.getElementById('CurrentClaim').ej2_instances[0];

    grid.element.addEventListener('keydown', function (event) {

        var closestTableCell = event.target.closest('td');

        if (event.keyCode === 38) {

            event.preventDefault();

            event.cancel = true;

        }

        if (event.keyCode === 40) {

            event.preventDefault();

            event.cancel = true;


        }

        if (event.keyCode === 39 && !ej.base.isNullOrUndefined(closestTableCell.nextSibling)) {

            editACell(closestTableCell.nextSibling);

        }

        if (event.keyCode === 37 && !ej.base.isNullOrUndefined(closestTableCell.previousSibling) && !grid.getColumnByIndex(parseInt(closestTableCell.previousSibling.getAttribute('data-colindex'))).isPrimaryKey) {

            editACell(closestTableCell.previousSibling);

        }

        if (event.keyCode === 40 && !ej.base.isNullOrUndefined(closestTableCell.closest('tr').nextSibling)) {

            editACell(closestTableCell.closest('tr').nextSibling.querySelectorAll('td')[parseInt(closestTableCell.getAttribute('data-colindex'))]);

        }

        if (event.keyCode === 38 && !ej.base.isNullOrUndefined(closestTableCell.closest('tr').previousSibling)) {

            editACell(closestTableCell.closest('tr').previousSibling.querySelectorAll('td')[parseInt(closestTableCell.getAttribute('data-colindex'))]);

        }

    });

}

function editACell(args) {

    var grid = document.getElementById('CurrentClaim').ej2_instances[0];

    grid.editModule.editCell(parseInt(args.getAttribute('index')), grid.getColumnByIndex(parseInt(args.getAttribute('data-colindex'))).field);

}


Am K 


7 Replies

KM Kishore Muthukrishnan Syncfusion Team April 15, 2025 11:12 AM UTC

Hi ,


Greetings from Syncfusion support,


You can prevent up/down arrow key for numeric textbox by overriding the keyDownHandler for NumericTextbox component. Please refer to the below code snippet for more information.



<script>

ej.inputs.NumericTextBox.prototype.keyDownHandler = function (e) {

        if (!this.readonly) 

            switch (e.keyCode) { 

                case 38: // Arrow Up

                case 40: // Arrow Down

                    e.preventDefault(); 

                    break;  

            } 

    };
</script>
@Html.EJS().Grid("CurrentClaim").DataSource(ds => ds.Url(gridDataSource).BatchUrl(batchUpdateUrl).Adaptor("UrlAdaptor")).ActionBegin("actionBegin").ActionComplete("actionComplete").AllowSorting().ToolbarClick("toolbarClick").Created("created").Load("load").AllowExcelExport().Columns(col =>

                    {

                        .  .  .

                    }).AllowPaging().PageSettings(

                        page => { page.PageSizes((new string[] { "10", "20", "50", "All" })); page.PageSize(20); }).AllowFiltering().FilterSettings(Filter =>

                { Filter.Type(Syncfusion.EJ2.Grids.FilterType.Excel); }

                        ).Toolbar(toolbarItems).Width("660").EditSettings(edit => { edit.AllowAdding(false).AllowEditing(true).AllowDeleting(false).Mode(Syncfusion.EJ2.Grids.EditMode.Batch); }).Render()


KB: https://support.syncfusion.com/kb/article/15681/disabling-mouse-wheel-and-arrow-key-interactions-in-angular-numerictextbox

If you need further assistance, feel free to let us know!


Regards,

Kishore Muthukrishnan



DH Dermot Heslin replied to Kishore Muthukrishnan April 22, 2025 11:58 AM UTC

Hi, this almost works, but I want to use the up and down arrows for navigation.

With the keyDownHandler, the value does not update before the focus changes.

Without the keyDownHandler, the values changes by 1 or -1 before the focus changes.

Code attc


Attachment: arrow_keys_4155f8c2.zip



KM Kishore Muthukrishnan Syncfusion Team April 23, 2025 10:26 AM UTC

Hi ,


To achieve your query regarding preventing the NumericTextBox from changing its value with arrow keys, but still allowing Up/Down arrows to move focus. Please follow the below instructions:


  1. Disabled value changes: We overrode the increment() and decrement() methods of the NumericTextBox. These methods are normally triggered when pressing the Up and Down arrow keys to increase or decrease the value. By overriding them with empty functions, we stop the value from changing:

ej.inputs.NumericTextBox.prototype.increment = function (step) { };
ej.inputs.NumericTextBox.prototype.decrement = function (step) { };


  1. Preserved default browser focus behavior: The original keyDownHandler inside the NumericTextBox includes e.preventDefault() when using arrow keys. This prevents the browser from moving focus to the next/previous field. We replaced that handler and removed the preventDefault(), allowing the browser to naturally move focus using the Up and Down keys.


ej.inputs.NumericTextBox.prototype.keyDownHandler = function (e) {

    if (!this.readonly) {

        switch (e.keyCode) {

            case 38: // Arrow Up

            case 40: // Arrow Down

                // No preventDefault, so focus can move

                break;

        }

    }

};


If you need further assistance, feel free to let us know!


Regards,

Kishore Muthukrishnan



DH Dermot Heslin April 23, 2025 12:53 PM UTC

Hi there

Thank you for your reply. When I implement this code, I lose any changes to the cell when I use the up or down arrow key. I would like the arrow keys to mimic the tab key behaviour - so that the new value is preserved after navigation. Can you please tell me how to achieve this?

Thank you

Dermot



KM Kishore Muthukrishnan Syncfusion Team April 24, 2025 09:42 AM UTC

Hi ,


We understand that you want to mimic tab key behavior for up/down arrow keys that focus moves to next/previous cell for NumericTextBox. You can achieve this by preventing default behavior and overriding existing behavior by setting focus on next/previous focusable elements. Please refer to the below code snippet for more information.


ej.inputs.NumericTextBox.prototype.keyDownHandler = function (e) {

        if (!this.readonly) {

            const isArrowUp = e.keyCode === 38;    // Arrow Up

            const isArrowDown = e.keyCode === 40;  // Arrow Down

    

            if (isArrowUp || isArrowDown) {

                e.preventDefault();

    

                const direction = isArrowUp ? -1 : 1;

                const focusable = Array.from(document.querySelectorAll(

                    'input:not(.e-numeric-hidden):not([type="hidden"]), button, select, textarea, [tabindex]:not([tabindex="-1"])'

                )).filter(el => 

                    !el.disabled && el.offsetParent !== null && getComputedStyle(el).visibility !== 'hidden'

                );

    

                const currentIndex = focusable.indexOf(document.activeElement);

                const nextIndex = currentIndex + direction;

    

                if (focusable[nextIndex]) {

                    focusable[nextIndex].focus();

                }

            }    


If you need further assistance, feel free to let us know!


Regards,

Kishore Muthukrishnan



DH Dermot Heslin replied to Kishore Muthukrishnan April 24, 2025 11:04 AM UTC

Thank you. In the end I needed to set the Step to zero for the NumericTextBox - this 



KM Kishore Muthukrishnan Syncfusion Team April 25, 2025 05:54 AM UTC

Hi ,


We are glad to hear that you have achieved your requirement. Please get back to us if you need further assistance.


Regards,

Kishore Muthukrishnan


Loader.
Up arrow icon