Home > Back-end >  cant get setSelectionRange to put the cursor at the beginning of the input
cant get setSelectionRange to put the cursor at the beginning of the input

Time:12-04

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.

CodePudding user response:

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/

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related