what I want to achieve is that every 4 digits, a space is typed in an input, automatically, all I find is using JQUERY but I use javascript vanila, and I don't know how to achieve it, the last thing I try is the following:
let creditNumber = document.getElementById("numbers")
creditNumber.addEventListener("keyup", function(event) {
var inputText = event.path[0].value;
document.getElementById("numeros").innerHTML = inputText
console.log(inputText.length)
if(inputText.length == 4 || inputText.length == 8 || inputText.length == 12) {
console.log("espacio aca")
}
})
What this returns me is that every fourth, eighth and twelfth digit that is entered in the input, it shows me "Space here" on the console, what I need to do is generate a space, but with inputText = " ";
it it does not work for me, I do not know how to do it,
Thanks for your help,
If you don't want to mess with regex you can use one of the functions proposed in this question on the English site to split the string of numbers into chunks .
Then once you have the chunks, join them through a space (but before joining each part of the chunk). To avoid strange behavior before you have to "clean" the spaces that you have placed before.
You can also use the input attribute
maxlength
to limit the number of characters the user can put in the input. In this case there are 19 because there are 4 groups of 4 -16- plus three spaces that separate those groups.Edit: Even if you want to look fancy you can add a validation to only allow numbers and with this also move the space sanitization part to this function.
How about you try my script?
Replace your code with mine: