I have 3 input field,when i write in the field, how to add space between every 2 number using the ID of the input, in javascript?
Any help please!
<input type="number" class="phone" placeholder="Phone" id="phone" />
<input type="number" class="phone" placeholder="Second Number" id="secondnumber" />
<input type="number" class="phone" placeholder="Fax" id="fax" />
i’m trying this script, but it’s not apply for all the input
const input = document.getElementById("phone") || document.getElementById("secondnumber") || document.getElementById("secondnumber");
input.addEventListener("input", () => input.value = formatNumber(input.value.replaceAll(" ", "")));
const formatNumber = (number) => number.split("").reduce((seed, next, index) => {
if (index !== 0 && !(index % 2)) seed += " ";
return seed + next;
}, "");
2
Answers
To add spaces between every two numbers in the input fields using JavaScript, you can modify your code as follows:
In this code, we assign separate event listeners to each input field and call the formatInputValue function whenever the input value changes. The formatInputValue function removes any existing spaces in the input value and then applies the formatNumber function to add spaces between every two numbers. The formatNumber function uses the reduce method to iterate over each character of the number and inserts a space after every second character.