skip to Main Content

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


  1. console.log(("123456789abcdefgh".match(/.{1,2}/g) || []).join(" "))
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search