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

后端 未结 7 919
我在风中等你
我在风中等你 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:23

    This is mostly a joke but here is a Vanilla JS version using the newest APIs as long as you have a modern browser, it should be bullet proof

    Here's what's happening:

    1. Select Elements, inputs, etc... (excluding disabled, hidden, etc...)
    2. Using the spread syntax, convert array (NodeList) to an object (here it's NodeObject)
    3. Loop through the Objects aka Elements aka Nodes
    4. Each iteration will pass the current element (Node) and the next element (NextNode) to an arrow function.
    5. Continue if NextNode is an element
    6. Then add a keypress event to the current element
    7. Inside the event:
      • Continue only if the enter key was pressed (using e.key NOT e.keyCode or e.which -- which are deprecated)
      • Stop the Form from being submitted
      • Focus the next element
      • If we can, Select the text in the next node

    And just like that you have some really unreadable code that is mostly parenthesis and arrow functions :)

    // NodeList of applicable inputs, select, button
    let NodesArray = document.querySelectorAll(`
                      #form input:not([disabled])[type]:not([type=\"hidden\"]),
                      #form select:not([disabled]),
                      #form button:not([disabled])[type=\"submit\"]
                    `);
    
    // Spread the array to an object so we can load the next node without 
    // keeping track of indexes (barf)
    (NodesObject => {
    
      // Node and NextNode are Elements.
      // You can update and get data if you want
      Object.keys(NodesObject).forEach(i => (({ Node, NextNode }) => {
    
        // Break if we dont have a NextNode
        if (NextNode === false) return;
    
    
        Node.addEventListener('keypress', KeyboardEvent => {
    
          // Only continue if event.key was "Enter"
          if (KeyboardEvent.key !== "Enter") return;
    
          // Dont submit, thx
          KeyboardEvent.preventDefault();
    
          // Do the thing
          NextNode.focus();
    
          // Not all elements have a select method
          if (typeof NextNode.select === 'function') NextNode.select();
        });
    
    
      })({
        Node:     NodesObject[i],
        NextNode: NodesObject[(parseInt(i) + 1)] ?? false
      }));
    
    })({ ...NodesArray });
    

提交回复
热议问题