Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
Disable default action on keyUp

In my form, I want to use keyboard arrow keys to move between the input fields.

Here is the Codesandbox example. (Click inside the last input field and use the UP arrow key to move up to the previous sibling input field.

Code:

  const arrowDownPosition = React.useRef();

  const getCurElePosition = (eTarget) => {
    const mum = eTarget.parentElement.parentElement;
    const parent = mum.parentElement;
    const children = Array.from(parent.children);
    let taskNum;
    children.forEach((el, i) => {
      const elChild = el.children[0].children[0];
      if (elChild === eTarget) {
        taskNum = i;
      }
    });
    return [taskNum, parent, children, mum];
  };

  const keyUpHandler = (e) => {
    e.preventDefault();
    if (e.key === "ArrowUp") {
      e.target.setSelectionRange(
        arrowDownPosition.current[0],
        arrowDownPosition.current[1]
      );
    }
  };

  const keyHandler = (e) => {
    e.stopPropagation();
    const eTarget = e.target;
    const [elePosition, parent, children, mum] = getCurElePosition(eTarget);
    if (e.key === "ArrowUp") {
      let previousSiblingRef;
      children.forEach((ele, i) => {
        if (ele == mum && i - 1 >= 0) {
          previousSiblingRef = i - 1;
        }
      });
      if (previousSiblingRef) {
        const { selectionStart, selectionEnd } = eTarget;
        arrowDownPosition.current = [selectionStart, selectionEnd];
        const previousSibling =
          children[previousSiblingRef].children[0].children[0];
        previousSibling.focus();
        previousSibling.setSelectionRange(selectionStart, selectionEnd);
      }
    }
  };

The above solution is a hacky way of solving the problem. You can see the caret move to the start of the previous input field before its moved to my intended position. I am using useRef to store the value.

This is because I am unable to stop the keyUp default handler before my code is run?

Thank you

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!