-4

I found this file that calculates the sum of two textbox values the problem is I need to show it in commas like 1000 > 1,000 in my total textbox.

Below is the code.

<!doctype html>
<html>
<head>
    <script>
        var x = 0;
        var y = 0;
        var z = 0;
        function calc(obj) {
            var e = obj.id.toString();
            if (e == 'tb1') {
                x = Number(obj.value);
                y = Number(document.getElementById('tb2').value);
            } else {
                x = Number(document.getElementById('tb1').value);
                y = Number(obj.value);
            }
            z = x + y;
            document.getElementById('total').value = z;

        }
    </script>
</head>
<form name="addem" action="" id="addem" >    

    <p><input type="text" id="tb1" name="tb1" onkeyup="calc(this)"/>1</p>
    <p><input type="text" id="tb2" name="tb2" onkeyup="calc(this)"/>2</p>
    <input type="text" id="total" name="total" value="0" />
</form>
</body>
</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Med
  • 1
  • 3

1 Answers1

0

You can use any library for formatting numbers such as Numeral.js

and your modified code is

<!doctype html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js" />
    <script>
        var x = 0;
        var y = 0;
        var z = 0;
        function calc(obj) {
            var e = obj.id.toString();
            if (e == 'tb1') {
                x = Number(obj.value);
                y = Number(document.getElementById('tb2').value);
            } else {
                x = Number(document.getElementById('tb1').value);
                y = Number(obj.value);
            }
            z = x + y;
            var string = numeral(z).format('0,0');
            document.getElementById('total').value = string;
        }
    </script>
</head>
<body>
<form name="addem" action="" id="addem" >    

    <p><input type="text" id="tb1" name="tb1" onkeyup="calc(this)"/>1</p>
    <p><input type="text" id="tb2" name="tb2" onkeyup="calc(this)"/>2</p>
    <input type="text" id="total" name="total" />
</form>
</body>
</html>
Farhan Haque
  • 991
  • 1
  • 9
  • 21