Skip to content
Advertisement

Adding space after every 3rd number in input

I want to add space after every 3rd number, but this code doesn’t work if the input is type="number". Does someone know how to modify the code to make it work even for type="number" ? Here is my input:

<input type="number" id="phone" autocomplete="off" placeholder="(+420)">

And also here is the script:

<script>
document.getElementById('phone').addEventListener('input', function (e) {
    e.target.value = e.target.value.replace(/[^dA-Z]/g, '').replace(/(.{3})/g, '$1 ').trim();
});
</script>

Advertisement

Answer

Try this:

function insertBlankAfterEveryThreeCharacters(str) {
  var str=str.split(" ").join("").split("");
  var formatted=[];
  while(str.length) {
    for(var i=0; i<3 && str.length; i++) {
      formatted.push(str.shift());
    }
    if(str.length) formatted.push(" ");
  }
  return formatted.join("");
}

Use in your event:

this.value=insertBlankAfterEveryThreeCharacters(this.value);

document.getElementById('phone').addEventListener('input', function (e) {
  this.value=insertBlankAfterEveryThreeCharacters(this.value);
});

function insertBlankAfterEveryThreeCharacters(str) {
  var str=str.split(" ").join("").split("");
  var formatted=[];
  while(str.length) {
    for(var i=0; i<3 && str.length; i++) {
      formatted.push(str.shift());
    }
    if(str.length) formatted.push(" ");
  }
  return formatted.join("");
}
<input id="phone">

<input type="number"... makes it so you can go up/down one = I assume not an intended result…
Your place holder has parentheses and a plus in it – It is not what you seem to be wanting in the solution…

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement