onkeyup javascript函数在输入字段上无法正常工作

时间:2015-07-09 10:25:30

标签: javascript forms events format onkeyup

我有一个将整数转换为印度卢比格式的函数。它适用于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,0,000而不是2,00,00,000

1 个答案:

答案 0 :(得分:0)

1)将onkeyup="numberWithCommas(this.value)"替换为onkeyup="numberWithCommas(this)"

2)由于我们现在通过引用传递元素,请执行以下操作:

&#13;
&#13;
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;
}
&#13;
No commas in here:
<input type="text" id="in_no1" onkeyup="numberWithCommas(this)" />
&#13;
&#13;
&#13;