HTML input field need to take characters from beginning when full

Viewed 78

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()">

2 Answers

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>


const demo = document.getElementById("demo")

demo.addEventListener("keyup", myFunction )
let cursor_position = 1
let can_update = false

function myFunction(e) { 
  let max = parseInt(demo.getAttribute('maxlength'), 10)
  if ( can_update ) {
    e.target.value = replaceAt(e.target.value, cursor_position - 1, e.key)
    demo.setSelectionRange(cursor_position, cursor_position);
    (cursor_position < max ) ? cursor_position++ : cursor_position = 1
  } else if (demo.value.length === max) { can_update = true }
}

const replaceAt = (str, index, replacement) => str.substr(0, index) + replacement + str.substr(index + replacement.length)
Related