put white spaces when entering an amount moneytype symfony

27 Views Asked by At

I would like to put spaces when entering an amount like this. Do I have to use javascript? Thank you for your help meenter image description here

1

There are 1 best solutions below

3
Shivam Saxena On

Yes if you are creating the program on the browser using html and js, you can use the following code to achieve it. By changing the template inside amountInput.oninput you can change the maximum amount.

HTML

<label>Montant Rechargement</label>
<br />
<input
  autocomplete="cc-number"
  id="amountInput"
  name="amountInput"
  type="tel"
  placeholder="1 000 000"
/>

JS

const amountInput = document.getElementById("amountInput");

amountInput.oninput = (e) => {
  let cursorPos = e.target.selectionStart
  let currentValue = e.target.value
  let cleanValue = currentValue.replace(/\D/g, "");
  let formatInput = patternMatch({
      input: cleanValue,
      template: "x xxx xxx xxx"
   });
  
  e.target.value = formatInput
  
  let isBackspace = (e?.data==null) ? true: false
  let nextCusPos = nextDigit(formatInput, cursorPos, isBackspace)
  
  amountInput.setSelectionRange(nextCusPos+1, nextCusPos+1);
};

function nextDigit(input, cursorpos, isBackspace) {
  if (isBackspace){
    for (let i = cursorpos-1; i > 0; i--) {
    if(/\d/.test(input[i])){
      return i
    }
  }
  }else{
    for (let i = cursorpos-1; i < input.length; i++) {
    if(/\d/.test(input[i])){
      return i
    }
  }
  }
  
  return cursorpos
}

function patternMatch({
  input,
  template
}) {
  try {

    let j = 0;
    let plaintext = "";
    let countj = 0;
    while (j < template.length) {
      // code block to be
      
      if (countj > input.length - 1) {
        template = template.substring(0, j);
        break;
      }

      if (template[j] == input[j]) {
        j++;
        countj++;
        continue;
      }

      if (template[j] == "x") {
        template = template.substring(0, j) + input[countj] + template.substring(j + 1);
        plaintext = plaintext + input[countj];
        countj++;
      }
      j++;
    }

    return template
 
  } catch {
    return ""
  }
}