How can I add a space after every 5th number (as user types) in the input field?
12345 56789 12345 56789
The limitation is that I cannot use any infrastructure like jQuery. This must be done using simple Javascript or CSS.
I also need to maintain the ability to remove the backspace and adjust the number or place the cursor anywhere and start fixing with backspace.
The following code is based on the answer here:
How to insert a space every 4 characters to register IBAN?
The back space does not work reliably.
function space(str, after) {
if (!str) {
return false;
}
after = after || 4;
var v = str.replace(/[^\dA-Z]/g, ''),
reg = new RegExp(".{" + after + "}", "g");
return v.replace(reg, function(a) {
return a + ' ';
});
}
var el = document.getElementById('pin');
el.addEventListener('keyup', function() {
this.value = space(this.value, 4);
});
<form>
<input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
<script>
</script>
</form>
Run codeHide result