0

I have a web page in which I input data into an <input />, like 1000 so I want it to look like 1,000 but it does not change the ID value it just show for only becuase I am using same the ID in other calculation so if 1,000 then it will show NaN... how can I avoid this?

<input type="text" id="test" onBlur="addCommas()">
<script>
    function addCommas(nStr){
        var offset = nStr.length % 3;
        if (offset == 0)
            return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
        else
            return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g,    ",$1");
    }
    alert(addCommas("1234567"));
</script>

I have got this code from a forum... does anyone have an idea how to make this function simple so that it just shows in input box but when I get the ID value it shows 1000?

Matt
  • 74,352
  • 26
  • 153
  • 180
  • http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript might help you – Pete Apr 25 '13 at 09:09
  • @Pete thanks for support can you please tell me how to use this method in mine id and how will it change display – Jdeveloper Iphone Apr 25 '13 at 09:10

1 Answers1

0

Test your value with this :

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

it will prevent your NAN's.

And use @Pete's link to know how to print a number with commas as thousands separators in JavaScript

EDIT About your comment : Then you can use a <input type="hidden" id="testValue" /> and store the real value in it.

So your code will look like :

<input type="text" id="test" onBlur="addCommas(this)">
<input type="hidden" id="testRealValue">
<script>
    function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
    function addCommas(input){
        nStr = input.value;
        if(!isNumber(nStr))return;
        document.getElementById("testRealValue").value = nStr;
        var offset = nStr.length % 3;
        if (offset == 0)
            input.value = nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
        else
            input.value = nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g,    ",$1");
    }
</script>

Here is the jsfiddle

Community
  • 1
  • 1
NeeL
  • 720
  • 6
  • 20