0

I want to set the focus to the next input when the user hits enter key. I have below jquery in $(ready) block:

$("body").on('keydown', ":input", focusHandler(Event, this)); 

focusHandler() looks like:

window.focusHandler = function focusHandler(event, control) {
    if (event.keyCode === 13) {
        if ($(control).attr("type") != "button") {
            event.preventDefault();
            var enabledInputs = $(":input:enabled");
            var idx = enabledInputs.index(control);
            enabledInputs.eq(idx+1).focus();
        }
    }
    else if (event.keyCode === 27) {
        event.preventDefault();
        var enabledInputs = $(":input:enabled");
        var idx = enabledInputs.index(control);
        enabledInputs.eq(idx-1).focus();
    }
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

But when the page is being loaded, I get TypeError: Cannot create property 'guid' on string ':input' error.

Lakmal Premaratne
  • 1,159
  • 7
  • 18
  • 34
  • 1
    You're setting the event handler to the *result* of calling `focusHandler(Event, this)`. Since it doesn't return a function, it will fail. – Heretic Monkey Nov 12 '18 at 18:42
  • @HereticMonkey But in https://api.jquery.com/on/, it is documented as: *A function to execute when the event is triggered.* – Lakmal Premaratne Nov 12 '18 at 18:47
  • 1
    @LakmalPremaratne On that api page, if you look at the second code snippet under **Direct and delegated event handlers** you will see the syntax you want. – Taplar Nov 12 '18 at 18:50
  • Right, and you're providing it with the result of a function that is triggered at the time of compiling, not a _reference_ to a function to execute when the event is triggered. To do that, you use the name of the function (e.g., `$("body").on('keydown', ":input", focusHandler)`). There are other ways of doing it, but they way you're doing it now, well, results in an error :). – Heretic Monkey Nov 12 '18 at 18:51
  • @HereticMonkey Thank you for your explanation. It helped me too to identify the problem... – Lakmal Premaratne Nov 13 '18 at 03:38
  • @Taplar Thank you and I would like to take this as the answer. But I cannot make a comment an answer. :( – Lakmal Premaratne Nov 13 '18 at 03:40

0 Answers0