How to advance to the next form input when the current input has a value?

前端 未结 10 1429
傲寒
傲寒 2020-11-30 04:08

I am having a form with lots of entries. I would like to change my focus to the next textbox, once I entered the value in the current textbox. and want to continue this proc

10条回答
  •  青春惊慌失措
    2020-11-30 04:12

    In the first question, you don't need an event listener on every input that would be wasteful.

    Instead, listen for the enter key and to find the currently focused element use document.activeElement

    window.onkeypress = function(e) {
        if (e.which == 13) {
           e.preventDefault();
           var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
           if (nextInput) {
              nextInput.focus();
           }
        }
    };
    

    One event listener is better than many, especially on low power / mobile browsers.

提交回复
热议问题