Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
no puedo obtener setSelectionRange para colocar el cursor al comienzo de la entrada

Hola,

tengo este codigo:

 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); } } });

cuando presiona ENTER, se supone que debe borrar la entrada del área de texto y devolver el cursor al inicio, pero no lo hará. En su lugar, el cursor permanece en la segunda línea. Aquí está el violín: https://jsfiddle.net/xbc0vong/

¿porqué es eso?

Gracias.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Utilice e.preventDefault(); para evitar el comportamiento predeterminado.

Prueba esto

 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); } } });

Caja de arena de código => https://jsfiddle.net/pa6cjweo/1/

about 4 years ago · Juan Pablo Isaza Report

0

Parece que se necesita un ligero retraso después de que se haya borrado el atributo .value . Usar setTimeout() funcionó.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!