Search code examples
javascripthtmlkeyevent

HTML input field need to take characters from beginning when full


I need a text box which when maxlength is reached, need to position cursor to beginning and on key input needs to replace the characters as keys are pressed. My sample code is below. I can get cursor to start of textbox when maxlength is reached, but the characters are not replaced. Please share any ideas on how I can change the default input field behavior.

https://jsfiddle.net/yd62jugk/7/

function myFunction() {  
  if (document.getElementById("demo").selectionStart === 
      parseInt(document.getElementById("demo").getAttribute('maxlength'), 10)) {
      document.getElementById("demo").setSelectionRange(0,0);  
  }
}
<p>Press keys.</p>
<input type="text" id="demo" maxlength=5 onkeyup="myFunction()">


Solution

  • const input = document.querySelector('input');
    const maxLength = Number(input.getAttribute('maxlength'));
    
    input.addEventListener('keydown',(e)=>{
      let value=input.value;
      let start=input.selectionStart;
      value[start+1]=e.keyCode; 
    
      input.setSelectionRange(start,start+1);
      input.value=value;
      if (start===maxLength){
        input.setSelectionRange(0,1);
      }
    });
    console.log(maxLength);
    <!DOCTYPE html>
    <html>
    <body>
    <p>Press a key inside the text field to set a red background color.</p>
    
    <input type="text" id="demo" maxlength="5">
    
    </body>
    </html>