Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda