Adding amounts together

Hello, I have a form which needs to add the total amount of each element together. The problem is that I cannot get it to add the value of the inputs that are programmatically entered. For example, I have a radio button which changes the text of the first input, which will then stop the inputs from adding. You can get a better understanding of what i’m trying to achieve by viewing it here - http://jsfiddle.net/lukem13/bbuyw/2/

So the two radio buttons will change the first input results which will be added together along with “tb2”, “tb3” and the buttons and displayed in the “Results” textbox, but if the user changes the text of the input manually, then this will also change the total of the “results” textbox.

The buttons value will be added to the total when the button is changed from “Add” to “Added!” So if the user clicks the first button and it has changed to “Added!” $6 will be added to the total amount.

I hope i explained it well enough for you guys??

Thanks,
Luke

Alright, let’s do this bit by bit:

You need some kind of update mechanism which adds the inputs together when triggered.
Let’s go with a form right now (although we can change it later).

Also, let’s go through the elements one by one and start with the text fields.

So, when the form is submitted we want to check if both text fields contain numerical values.
If not we want to replace their values with zero and add the value of the text fields together.

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Total form elements</title>
  </head>

  <body>

  <form id="myForm">
    <div>
      <label for="amount1">$</label>
      <input type="text" id="amount1" />
    </div>
    <div>
      <label for="amount1">$</label>
      <input type="text" id="amount2" />
    </div>

    <div>
      Total: <input type="text" id="total" readonly />
    </div>

    <input type="submit" value="add"/>
  </form>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      $("myForm").on("submit", function(){
        // get value from input 1 and store it in a variable
        // check it is a number
        // if not, set the value to zero

        // repeat for input 2

        // Update the value of the #total
      });
    </script>
  </body>
</html>

See how you get on with that and then we can move on to incorporating the other elements.

Hello Pullo,
Something like this?

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Total form elements</title>
  </head>

  <body>

  <form id="myForm">
    <div>
      <label for="amount1">$</label>
      <input type="text" id="amount1" onkeyup="getValues(1)" value="0"/>
    </div>
    <div>
      <label for="amount1">$</label>
      <input type="text" id="amount2" onkeyup="getValues(2)" value="0" />
    </div>

    <div>
      Total: <input type="text" id="total" readonly />
    </div>

    <input type="submit" value="add"/>
  </form>

    <script src="jquery-latest.min.js" type="text/javascript"></script>
    <script>
     function getValues(val){

var val1=parseInt(document.getElementById("amount1").value);
var val2=parseInt(document.getElementById("amount2").value);

var totalValue = val1 + val2;

document.getElementById("total").value = totalValue;

}*******
    </script>
  </body>
</html>

Don’t use parseInt() - that is for converting numbers to base 10 from other bases between 2 and 36.

To convert a string to a number use Number() or do it like this:

var val1=+document.getElementById("amount1").value;

That’s going in the right direction.

A couple of points:

I would use Number() instead of parseInt().
This is because Number() is used for type conversion, which is what we need here.
You can read more here: http://stackoverflow.com/questions/4090518/string-to-int-use-parseint-or-number

As you seem to be including jQuery anyway (in your Fiddle for example), I would take advantage of it here.

Here’s how I would do things so far:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Total form elements</title>
    <style>
      fieldset{ margin: 10px; }
    </style>
  </head>
  
  <body>
  
  <form id="myForm">
    <fieldset>
      <legend>Text inputs:</legend>
        <div>
          <label for="amount1">$</label>
          <input type="text" id="amount1" value="0"/>
        </div>
        <div>
          <label for="amount1">$</label>
          <input type="text" id="amount2"  value="0"/>
        </div>
      </fieldset>
      
      <fieldset>
        <legend>Radio buttons and text input:</legend>
        <div>
          <label><input type="radio" name="radio" value="2" class="radiobutton" />$2</label>
          <label><input type="radio" name="radio" value="5" class="radiobutton" checked="checked" />$5</label>
        </div>
        <div>
          <label for="amount3">$</label>
          <input id="amount3" type="text" value="5" />
        </div>
      </fieldset>
      
      <fieldset>
        <legend>Grand total:</legend>
        <div>
          <label for="total">Total:</label>
          <input type="text" id="total" value="0" readonly />
        </div>
      </fieldset>      
      
      <input type="submit" value="Add"/>
      <input type="reset" value="Reset!">
    </form>
  
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      $(".radiobutton").on("change", function(){
        $("#amount3").val($(this).val())
      });
      
      $("#myForm").on("submit", function(e){
        e.preventDefault();
        
        var amount1 = Number($("#amount1").val()),
            amount2 = Number($("#amount2").val()),
            amount3 = Number($("#amount3").val()),
            sum;
        
        if(isNaN(amount1)){
          amount1 = 0;
          $("#amount1").val(amount1)
        }
        
        if(isNaN(amount2)){
          amount2 = 0;
          $("#amount2").val(amount2)
        }
        
        sum = amount1 + amount2 + amount3;
        $("#total").val(sum);
      });
    </script>
  </body>
</html>

I’ve also added an event handler for the radio buttons (in-line JavaScript is normally to be avoided) and have added the total for the radio buttons to what we have so far.

Why don’t you now have a stab at the buttons?

I would use a data attribute to store the button’s value (e.g. data-value = "6"), then on submit check the button’s text value (e.g. $("#button1").txt()) to determine what to add to the total.

Edit: felgall beat me to it :slight_smile:

Thanks for the replys guys!

I’ve got the button to display the data-value but it is displaying constantly and i’m not sure how to display the value just onclick?

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Total form elements</title>
    <style>
      fieldset{ margin: 10px; }
    </style>
  </head>

  <body>

  <form id="myForm">
    <fieldset>
      <legend>Text inputs:</legend>
        <div>
          <label for="amount1">$</label>
          <input type="text" id="amount1" value="0"/>
        </div>
        <div>
          <label for="amount1">$</label>
          <input type="text" id="amount2"  value="0"/>
        </div>
      </fieldset>

      <fieldset>
        <legend>Radio buttons and text input:</legend>
        <div>
          <label><input type="radio" name="radio" value="2" class="radiobutton" />$2</label>
          <label><input type="radio" name="radio" value="5" class="radiobutton" checked="checked" />$5</label>
        </div>
        <div>
          <label for="amount3">$</label>
          <input id="amount3" type="text" value="5" />
        </div>
      </fieldset>
       <fieldset>
        <legend>Button change:</legend>
        <div>
          <button type="button" class="add-btn" data-text-swap="Added!" id="button1" data-value = "6">Add</button>
          <button type="button" class="add-btn" data-text-swap="Added!" id="button2" data-value = "7">Add</button>
                </div>
      </fieldset>


      <fieldset>
        <legend>Grand total:</legend>
        <div>
          <label for="total">Total: £</label>
          <span  id="total">5</span>
        </div>
      </fieldset>

      <input type="submit" value="Add"/>
      <input type="reset" value="Reset!">
    </form>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
     $("button").on("click", function() {
        var el = $(this);
        if (el.text() == el.data("text-swap")) {
          el.text(el.data("text-original"));
        } else {
          el.data("text-original", el.text());
          el.text(el.data("text-swap"));
        }
        updateButtons();
      });

      $(".radiobutton").on("change", function(){
        $("#amount3").val($(this).val())
      });


      $("#myForm").on("submit", function(e){
        e.preventDefault();

               var amount1 = Number($("#amount1").val()),
            amount2 = Number($("#amount2").val()),
            amount3 = Number($("#amount3").val()),
            amount4 = Number($("#button1").attr('data-value')),
            amount5 = Number($("#button1").attr('data-value')),
            sum;



        if(isNaN(amount1)){
          amount1 = 0;
          $("#amount1").val(amount1)
        }

        if(isNaN(amount2)){
          amount2 = 0;
          $("#amount2").val(amount2)
        }

        sum = amount1 + amount2 + amount3 + amount4 + amount5;
        $("#total").text(sum);
      });
    </script>
  </body>
</html>

Also, how do i make the results appear automatically (without clicking the submit button), i’m presuming its something like this?

$("#myForm").change(function(e)

Only problem with this code is that you have to click out of the input before the results are updated?

Thanks for all your help Pullo!

Hi there,

I’m in a rush this morning, so apologies in advance for the brief post.

I would now move all of the logic that calculates the total into its own function, like this:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Total form elements</title>
    <style>
      fieldset{ margin: 10px; }
    </style>
  </head>

  <body>

  <form id="myForm">
    <fieldset>
      <legend>Text inputs:</legend>
        <div>
          <label for="amount1">$</label>
          <input type="text" id="amount1" value="0"/>
        </div>
        <div>
          <label for="amount1">$</label>
          <input type="text" id="amount2"  value="0"/>
        </div>
      </fieldset>

      <fieldset>
        <legend>Radio buttons and text input:</legend>
        <div>
          <label><input type="radio" name="radio" value="2" class="radiobutton" />$2</label>
          <label><input type="radio" name="radio" value="5" class="radiobutton" checked="checked" />$5</label>
        </div>
        <div>
          <label for="amount3">$</label>
          <input id="amount3" type="text" value="5" />
        </div>
      </fieldset>

      <fieldset>
        <legend>Button change:</legend>
        <div>
          <button type="button" class="add-btn" data-text-swap="Added!" id="button1" data-value="6">Add 6</button>
          <button type="button" class="add-btn" data-text-swap="Added!" id="button2" data-value="7">Add 7</button>
        </div>
      </fieldset>

      <fieldset>
        <legend>Grand total:</legend>
        <div>
          <label for="total">Total: £</label>
          <span  id="total">5</span>
        </div>
      </fieldset>

      <input type="submit" value="Add"/>
      <input type="reset" value="Reset!">
    </form>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
      function updateTotal(){
        var amount1 = Number($("#amount1").val()),
            amount2 = Number($("#amount2").val()),
            amount3 = Number($("#amount3").val()),
            amount4 = Number($("#button1").data('value')),
            amount5 = Number($("#button2").data('value')),
            sum;

        if(isNaN(amount1)){
          amount1 = 0;
          $("#amount1").val(amount1)
        }

        if(isNaN(amount2)){
          amount2 = 0;
          $("#amount2").val(amount2)
        }

        if($("#button1").text() != $("#button1").data("text-swap")){
          amount4 = 0;
        }

        if($("#button2").text() != $("#button2").data("text-swap")){
          amount5 = 0;
        }

        sum = amount1 + amount2 + amount3 + amount4 + amount5;
        $("#total").text(sum);
      }

     $("button").on("click", function() {
        var el = $(this);
        if (el.text() == el.data("text-swap")) {
          el.text(el.data("text-original"));
        } else {
          el.data("text-original", el.text());
          el.text(el.data("text-swap"));
        }
        updateTotal();
      });

      $(".radiobutton").on("change", function(){
        $("#amount3").val($(this).val())
      });

      $("#myForm").on("submit", function(e){
        e.preventDefault();
        updateTotal();
      });
    </script>
  </body>
</html>

This will pave the way for having the total update whenever anything changes.
Have a look at what I’ve done and let me know if you have any questions.

I’ll post more later.

If you are using jQuery, you can use the change event on the form element, because in jQuery the event bubbles.

$("#myForm").on("change", function(){
  updateTotal();
});

If you are using plain JavaScript, the change event does not bubble (at least not cross browser).
So you would have to attach the event handler to each input element separately.

If you make that final change as detailed above, things should now work as you desire.
If you start to add many more form elements, let me know and we can make some of the functions more generic.

HTH

Woo! Thank you Pullo! Works perfectly :slight_smile: