简体   繁体   中英

onkeyup javascript function does not work properly on input field

I have a function to convert an integer to indian rupees format. It works on onclick event function and give it result, but when it is apply on onkeyup event it doesn't work. Where is the problem?

my function is below.

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 is

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

if we create a another function like

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

}

and html change to

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

it works but the result is like 2,0,0,0,0,000 instead of 2,00,00,000

1) Replace onkeyup="numberWithCommas(this.value)" with onkeyup="numberWithCommas(this)" .

2) Since we are passing the element by reference now, do this:

 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)" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM