How to move focus on next field when enter is pressed?

后端 未结 7 910
我在风中等你
我在风中等你 2020-12-29 06:02

Can you please tell me how to move focus on to the next field when the enter key is press? I use the dform plugin (which converts JSON to a form).

I Go

相关标签:
7条回答
  • 2020-12-29 06:32

    Ill created a non-jQuery version. So only pure Javascript; https://jsfiddle.net/mm0uctuv/2/

    Javascript:

    var inputs = document.querySelectorAll("input,select");
    for (var i = 0 ; i < inputs.length; i++) {
       inputs[i].addEventListener("keypress", function(e){
          if (e.which == 13) {
             e.preventDefault();
             var nextInput = document.querySelectorAll('[tabIndex="' + (this.tabIndex + 1) + '"]');
             if (nextInput.length === 0) {
                nextInput = document.querySelectorAll('[tabIndex="1"]');
             }
             nextInput[0].focus();
          }
       })
    }
    

    HTML:

    <form>
       Field 1: <input type="text" tabindex="1"><br>
       Field 3: <input type="text" tabindex="3"><br>
       Field 2: <input type="text" tabindex="2">
    </form>
    
    0 讨论(0)
提交回复
热议问题