输入金额时输入空格 金钱类型 symfony

问题描述 投票:0回答:1

我想在输入这样的金额时添加空格。我必须使用 JavaScript 吗? 谢谢你对我的帮助enter image description here

jquery symfony-forms
1个回答
0
投票

是的,如果您使用html和js在浏览器上创建程序,您可以使用以下代码来实现。通过更改

amountInput.oninput
内的模板,您可以更改最大金额。

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 ""
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.