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

212
Visualizações
cant get setSelectionRange to put the cursor at the beginning of the input

Hi,

I have this code:

inputform.addEventListener('keypress', function(e) {
 const tgt = e.target;
 
 if (tgt.id==="usermsg") {
  if (e.which == 13 && !e.shiftKey && tgt.value) {
    tgt.value = '';
    tgt.setSelectionRange(0,0);
  }
 }
});

as you hit ENTER its supposed to clear the textarea input and return the cursor to the start but it wont do it. Instead, the cursor stays at the second line. Here is the fiddle: https://jsfiddle.net/xbc0vong/

why is that?

Thank you.

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

0

Use e.preventDefault(); to avoid default behavior.

Try this

inputform.addEventListener('keypress', function(e) {
 const tgt = e.target;
 
 if (tgt.id==="usermsg") {
  if (e.which == 13 && !e.shiftKey && tgt.value) {
    e.preventDefault();
    tgt.value = '';
    tgt.setSelectionRange(0,0);
  }
 }
});

Code sandbox => https://jsfiddle.net/pa6cjweo/1/

about 4 years ago · Juan Pablo Isaza Relatório

0

It appears that a slight delay is needed after the .value attribute has been cleared. Using setTimeout() worked.

const inputForm = document.forms[0];


inputForm.addEventListener('keypress', (e) => {
  const tgt = e.target;
  if (tgt.id === 'userMsg' && e.keyCode === 13) {
    tgt.value = '';
    setTimeout(() => {
      tgt.focus();
      tgt.setSelectionRange(0, 0);
    }, 0);
  }
});
<form id="inputForm">
  <textarea id="userMsg"></textarea>
</form>

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