Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add space between every 2 number?

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;
        }, "");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To add spaces between every two numbers in the input fields using JavaScript, you can modify your code as follows:

const phoneInput = document.getElementById("phone");
const secondNumberInput = document.getElementById("secondnumber");
const faxInput = document.getElementById("fax");

// Add event listener to each input field
phoneInput.addEventListener("input", () => formatInputValue(phoneInput));
secondNumberInput.addEventListener("input", () => formatInputValue(secondNumberInput));
faxInput.addEventListener("input", () => formatInputValue(faxInput));

function formatInputValue(input) {
  input.value = formatNumber(input.value.replaceAll(" ", ""));
}

function formatNumber(number) {
  return number.split("").reduce((seed, next, index) => {
    if (index !== 0 && !(index % 2)) seed += " ";
    return seed + next;
  }, "");
}

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading