Onkeyup javascript函数在输入字段上不能正常工作

onkeyup javascript function does not work properly on input field

本文关键字:常工作 工作 不能 函数 javascript 输入 字段 Onkeyup      更新时间:2023-09-26

我有一个将整数转换为印度卢比格式的函数。它工作在onclick事件功能,并给它的结果,但当它是onkeyup事件应用它不工作。问题在哪里?

我的功能如下。

function numberWithCommas(x) {
    x = x.replace(",", '');
    x = x.toString();
    var lastThree = x.substring(x.length - 3);
    var otherNumbers = x.substring(0, x.length - 3);
    if (otherNumbers != '')
        lastThree = ',' + lastThree;
    var res = otherNumbers.replace(/'B(?=('d{2})+(?!'d))/g, ",") + lastThree;
    return res;
}

function numberformat() {
    var n = document.getElementById('in_no').value;
    alert(numberWithCommas(n));
}
html是

<input type="text" id="in_no" />
<button onclick="numberformat()">Test</button>
<input type="text" id="in_no1" onkeyup="numberWithCommas(this.value)" />

如果我们创建另一个函数,如

    function numberformat1(id){
    var n = document.getElementById(id).value;
    var n = numberWithCommas(n);
  document.getElementById('in_no1').value = n;

}

和HTML更改为

    <input type="text" id="in_no1" onkeyup="numberformat1('in_no1')"/>

可以,但是结果是2,0,0,0,0000而不是2,0,00000

1)用onkeyup="numberWithCommas(this)"代替onkeyup="numberWithCommas(this.value)"

function numberWithCommas(x) {
  var elem = x;
  var x = x.value.replace(/,/g, '');
  var lastThree = x.substring(x.length - 3);
  var otherNumbers = x.substring(0, x.length - 3);
  if (otherNumbers != '')
    lastThree = ',' + lastThree;
  var res = otherNumbers.replace(/'B(?=('d{2})+(?!'d))/g, ",") + lastThree;
  elem.value = x;
}
No commas in here:
<input type="text" id="in_no1" onkeyup="numberWithCommas(this)" />