hey guys, so im trying to auto calculate two textfields. like for example i have textfield A and textfield B and also a <span> tag. the span tag is default zero. when user inputs A as 5 the <span> tag becomes 5. then when user inputs B as 2, A and B auto calculate and <span> becomes 7. but its not working for this coding that i have. it doesnt add up instead it becomes 52 instead of 7. i think the hidden input text is in the way but i dont know how to work around that.

coding:

<html>
<head>
<script type="text/javascript">

    function calculateTotal() {

        var totalAmt = document.addem.total.value;
        totalR = eval(totalAmt + document.addem.tb1.value);

        document.getElementById('update').innerHTML = totalR;
    }
    function calculateTotal1() {

        var totalAmt = document.addem.tb1.value;
        totalR = eval(totalAmt + document.addem.tb2.value);

        document.getElementById('update').innerHTML = totalR;
    }

</script>
</head>

<form name="addem" action="" id="addem" >    
    <span id="update">0</span>
    <p><input type="text" name="tb1" onkeyup="calculateTotal()"/>first textbox</p>
    <p><input type="text" name="tb2" onkeyup="calculateTotal1()"/>second textbox</p>
    <input type="hidden" name="total" value="0" />
</form>
</body>
</html>

This is very similar to another recent discussion:
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/467834/auto-calculate

The suggested approach that I provided in the other thread was to use one function instead of two. Send the input element to the function, figure out which element you are working with, then extract the value from the input element, convert into a number so you can add them together. The issue you are having is that the numbers are not being added. this is because they are still being treated as strings and you are simply concatenating them.

Here is a solution that works, feel free to adapt to your 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;
            document.getElementById('update').innerHTML = z;
        }
    </script>
</head>
<form name="addem" action="" id="addem" >    
    <span id="update">0</span>
    <p><input type="text" id="tb1" name="tb1" onkeyup="calc(this)"/>first textbox</p>
    <p><input type="text" id="tb2" name="tb2" onkeyup="calc(this)"/>second textbox</p>
    <input type="hidden" id="total" name="total" value="0" />
</form>
</body>
</html>

Thank you so much!

i have one question. what if i have a lot of text fields? im not very good with if..else statements. :s

Well, if you take a look at the other discussion (link posted above), in that case there were many input elements (text fields). In addition, the solution had the ability to add many more on the fly, client side.

The solution addressed this issue by having these textboxes arranged in a table/grid, several per row. Each row had a unique identifier in the ID.

So in the javascript function, aside from extracting the ID, the ID was split to seperate the id name and id row number.

So, i dont know if that solution applies to your scenario since you only mentioned "a lot of text fields".

well um the textboxes are there for user to fill in the price of something.

example:

Shoe : textbox
Table : textbox
Car : textbox
Mirror : textbox
Laptop : textbox
Books : textbox
Total : textbox (shows the total as the inputs are keyed in)

these are in a table in a form of course. then below the table will be a save button to save the input in the database.

hope that explains what im trying to do.

The easiest solution is to have one button that calls a function to add up all of the values. If you try to do the adding in real time via keyup, then it gets more complicated as you have experienced.

i dont mind complicated as long as its explained. id have to use jquery instead of js right?

So jQuery is actually a javascript library. Anyway, if you want to add in real time as the the user keys in the information, I suspect that it would be easier to use jQuery and have a function that simply loops through the input elements within the form, adding their values during the loop.

Are you familiar with jQuery? Loops?

I could be off and I do not want to guide you in the wrong direction, but this is what comes to mind as far as a possible solution.

not really. but no worries. im sure there are some examples i can find throughout the internet. thanks :)

Actually, i found some examples pretty quickly and adapted them to your example. The concept i had mentioned before worked as expected..

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>     

<table>
<tr><td>Shoe</td><td><input class="txtBox" type="text" name="shoe" /></td></tr>
<tr><td>Table</td><td><input class="txtBox" type="text" name="table" /></td></tr>
<tr><td>Car</td><td><input class="txtBox" type="text" name="car" /></td></tr>
<tr><td>Mirror</td><td><input class="txtBox" type="text" name="mirror" /></td></tr>
<tr><td>Laptop</td><td><input class="txtBox" type="text" name="laptop" /></td></tr>
<tr><td>Books</td><td><input class="txtBox" type="text" name="books" /></td></tr>
<tr><td>Total</td><td><input type="text" id="total" name="total" value="0" /></td></tr>
</table>

<script>
$(document).ready(function(){
  var total = 0;
  $('.txtBox').keyup(function(){
    $('.txtBox').each(function() {
      var txtBoxVal = $(this).val();
      total = total + Number(txtBoxVal);
    });
  $('#total').val(total);
  total = 0;
  });

});
</script>
</body>
</html>

wow thanks JorgeM that was fast thanks! will try it out now

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.