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

180
Visualizações
Key press shows the key character

I have a search box which is by default not autofocused. So i am putting a keypress event on the body i.e. when forward slash (/) is pressed the search box should be in focus. Although on key press it puts the search box in focus but also puts the "/" in the search box.

body.onkeypress = (e) => {
    if(e.which === 47) {
        searchInput.focus()
    }
} 

How should I fix this?

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

0

Use preventdefault to prevent the '/' from being typed.

Make sure you do this in your if statement, otherwise all characters get blocked.

body.onkeypress = (e) => {
    if(e.which === 47) {
        e.preventDefault()
        searchInput.focus()
    }
} 

https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

about 4 years ago · Juan Pablo Isaza Relatório

0

  <body id="body">
  <input type="text" id="elementid" />
</body>
<script>
  document.onkeypress = (e) => {
    if (e.which === 47) {
      document.getElementById("elementid").focus();
      setTimeout(() => {
        str = document.getElementById("elementid").value = document
          .getElementById("elementid")
          .value.slice(0, -1);
      });
    }
  };
</script>
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