jQuery: How to capture the TAB keypress within a Textbox

前端 未结 9 1471
迷失自我
迷失自我 2020-11-30 19:32

I want to capture the TAB keypress, cancel the default action and call my own javascript function.

9条回答
  •  有刺的猬
    2020-11-30 19:44

    An important part of using a key down on tab is knowing that tab will always try to do something already, don't forget to "return false" at the end.

    Here is what I did. I have a function that runs on .blur and a function that swaps where my form focus is. Basically it adds an input to the end of the form and goes there while running calculations on blur.

    $(this).children('input[type=text]').blur(timeEntered).keydown(function (e) {
            var code = e.keyCode || e.which;
            if (code == "9") {
                window.tabPressed = true;
                // Here is the external function you want to call, let your external
                // function handle all your custom code, then return false to
                // prevent the tab button from doing whatever it would naturally do.
                focusShift($(this));
                return false;
            } else {
                window.tabPressed = false;
            }
            // This is the code i want to execute, it might be different than yours
            function focusShift(trigger) {
                var focalPoint = false;
                if (tabPressed == true) {
                    console.log($(trigger).parents("td").next("td"));
                    focalPoint = $(trigger).parents("td").next("td");
    
                }
                if (focalPoint) {
                    $(focalPoint).trigger("click");
                }
            }
        });
    

提交回复
热议问题