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

214
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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