Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
Tabbing to next input using querySelector

I am trying to have the input fields tab over to the next field once maxlength is met but I keep getting an error Failed to execute 'querySelector' on 'Document': 'name=2' is not a valid selector.. Ive read over mozialla's explanation of a querySelector and I've tried using the elements id to focus() on but that gives the same error. I guess Im not understanding how to properly craft a selector to pass to the querySelector.

My Input fields ill only show 2 i have 3:


    <Input
              onChange={dateChange("month")}
              value={date.month}
              id="1"
              maxLength={2}
              type="number"
            />
            <span className="sep">/</span>
            <Input
              onChange={dateChange("day")}
              value={date.day}
              name="2"
              id="2"
              maxLength={2}
              type="number"
            />

My onChange:


    const dateChange = (field) => (e) => {
    
            const fieldIndex = e.target.name;
            let fieldIntIndex = parseInt(fieldIndex, 10);
            // format to fit
            let value = e.target.value;
          
            if (value.length === e.target.maxLength) {
              if (fieldIntIndex < 3) {
                const nextfield = document.querySelector(
                  `name=${fieldIntIndex + 1}`
                );
                console.log(nextfield);
                if (nextfield !== null) {
                  nextfield.focus();
                }
              }
            }
        
            const d = { ...date, [field]: value };
            setDate(d);
            debounceCallback(handleDateInputChange, d);
          };

Im still learning so any advice on this would be great :) thanks in advance!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First of all, I think that it is incorrect to set event listeners like this:

onChange={dateChange("month")}

If you do it that way, you actually execute that function during rendering of the page. The function should be executed when the event occurs. The correct way to do this would be:

onChange={dateChange}

If you also wanted to add parameters to your function then you should do it like this:

onChange={dateChange.bind(this, "month")}

Moreover, regarding the query selector, I think the correct syntax would be:

const nextfield = document.querySelector(`input[name='${fieldIntIndex + 1}']`);

Your name prop is set to an input element, so we use input[name].
Also name has a string value, so we use input[name=''].
Finally we want to set name value parametrically, so we use `input[name='${parameter}']`.

You can find the MDN documentation of bind JavaScript function here and the documentation of querySelector here.

Edit: Another alternative for navigating among inputs would be the tabindex attribute. You can find more about it here.

about 4 years ago · Juan Pablo Isaza Relatório

0

Name is a string So i think you should do it like this(add brackets) name='${fieldIntIndex + 1}'

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda