Thursday 19 July 2012

how to get sum of 2 or more text box values in javascript

ADD TWO OR MORE TEXT BOX VALUES IN JAVA SCRIPT

Generally we will add text box values  in java script as follows

 Test out with the 2 Text boxes , to see what yours should do. Enter a 2 in the first box, and a 2 in the second box. Then third Text Box will get updated by sum value.


Here we are using key press event to validate and allow only numbers, Key Up event to sum of the values and update in third text box.

so to ADD two or More text box values in java script follow this code :-


JAVA SCRIPT


<script type="text/javascript" language="javascript">
 
        function AllowOnlyNumbers(obj, e) {
            var key = window.event ? e.keyCode : e.which;
            if ((key > 45 && key < 58) || key == 8) {
                if (key == 47) {
                    return false;
                }
            }
            else {
                return false;
            }
            if (obj.value == "") {
                if (key == 46) {
                    return false;
                }
            }
            var DecimalCount = 0;
            for (d = 0; d < obj.value.length; d++) {
                var Character = obj.value.charAt(d);
                if (Character == ".") {
                    DecimalCount++;
                }
            }
            if (key == 46) {
                if (DecimalCount == 1) {
                    return false;
                }
            }
        }
        function SumValue() {
            var txtbox1 = document.getElementById("TextBox1").value;
            if (txtbox1 == "" || txtbox1 == ".") {
                txtbox1 = 0;
            }
            var txtbox2 = document.getElementById("TextBox2").value;
            if (txtbox2 == "" || txtbox2 == ".") {
                txtbox2 = 0;
            }
            var txtbox3 = document.getElementById("TextBox3");
            txtbox3.value = parseFloat(txtbox1) + parseFloat(txtbox2);
        }
     
    </script>