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

213
Views
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 answers
Answer question

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 Report

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