0

I have three DIV whose content are integer values and are updated frequently from another source. My main idea here was to take the content of the three divs parse it into float or integer , add them and display the total in another div. I am looking forward to handle the content in div using a onchange() function, because the the content in them will be changing frequently. Below is my code, its currently not working, i will really appreciate it if you give me a hand of help with this. The content in this divs will be frequently updated using a text input, you can create a text inout that manipulates the first div then displays the whole sum Thanks in advance.

<script>
    function total() {
  var value1 = parseFloat($('#div1').innerHTML ()) || 0;
  var value2 = parseFloat($('#div2').innerHTML ()) || 0;
  var value3 = parseFloat($('#div1').innerHTML ()) || 0;
  var total;
 total=value1 + value2 + value3;
  $('#total').html(total);
}
  </script>  
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

</head>
<body >
  <div id="mywraper">
      <div id="div1" onchange="total()">
     4
      </div>
      <div id="div2"  onchange="total()">
     5
      </div>
   <div id="div2" onchange="total()">
     6
      </div>
</div>
 <div id="total_div">
    Total $<span id="total"></span>
  </div>
</body>
</html>
Evanson
  • 3
  • 5
  • jQuery's object does not have method `.innerHTML()`. Use `.html()` instead. – Regent Mar 03 '15 at 09:54
  • or use the `.text()` - function – empiric Mar 03 '15 at 09:57
  • Also, you have duplicated ID's, it will not work... Similar problem explained here: http://stackoverflow.com/questions/6676186/use-onchange-in-a-div – sinisake Mar 03 '15 at 10:04
  • 1
    First of all onChange will not work with div as mentioned by Pete. instead call the total function from where you are really changing the div's value. and use .text() as mention by @empiric or .html() – Iftikhar Ali Ansari Mar 03 '15 at 10:04
  • Yes, onChange requires user input to detect a change, so you should stick the total function into what ever function updates the values in the first place. Anyhow, [you could do something more dynamic, like this this](http://jsfiddle.net/lollero/yt044Lju/) **|||** [This is the same as the prior example, I just removed all the comments and optional lines](http://jsfiddle.net/lollero/yt044Lju/1/) **|||** [Here I just added more divs](http://jsfiddle.net/lollero/yt044Lju/2/) to show that you don't have to change the javascript, if the amount of divs changes... – Joonas Mar 03 '15 at 11:59

4 Answers4

0

Use this html()

<script>
    function total() {
  var value1 = parseFloat($('#div1').html()) || 0;
  var value2 = parseFloat($('#div2').html()) || 0;
  var value3 = parseFloat($('#div1').html()) || 0;
  var total;
 total=value1 + value2 + value3;
  $('#total').html(total);
}
  </script>  
I'm Geeker
  • 4,601
  • 5
  • 22
  • 41
0

Use text() instead of innerHTML, like so:

<script>
    function total() {
      var value1 = parseFloat($('#div1').text()) || 0;
      var value2 = parseFloat($('#div2').text()) || 0;
      var value3 = parseFloat($('#div1').text()) || 0;
      var total;
      total=value1 + value2 + value3;
      $('#total').html(total);
    }
</script>  
  • please expand on your answer, showing how and *why* it solves the problem posed by the question - this will help others in the future, and you're more likely to get an upvote! – Our Man in Bananas Mar 03 '15 at 10:02
0

Try this:

 function total() {
    // fetch text using 'text' method and then convert string into number using '+' operator
    var value1 = +$('#div1').text() || 0;
    var value2 = +$('#div1').text() || 0;
    var value3 = +$('#div1').text() || 0;
    var total = value1 + value2 + value3;
    $('#total').html(total);
}

http://jsfiddle.net/uxajjk1b/2/

Mohit Pandey
  • 3,679
  • 7
  • 26
  • 38
0

I didn't really want to answer, as this might be difficult to solve due to the fact that we have no idea how the values are updated in the first place. However, I ended up doing relatively extensive example, so here we are.

So as mentioned before, onChange requires user input or action to detect any change. So that means your total() would only trigger once when the page is loaded ( assuming it's placed right before </body> ).

The best method would be to also stick the total() inside the original function that changes the values inside the html elements. This way total() is also triggered each time.


I couldn't resist making the total() more dynamic. This way, if you add or remove those child divs, the javascript won't need to be updated.

Here's a link to the original jsfiddle

var parentContainer = $('#mywraper');

function total() {

    var values = {}; // Optional****
    var total = 0;

    // Loops through parent containers children ( in this case div elements ).
    parentContainer.children().text(function( i, val ) {

        var value = parseInt( val );

        // Creates a variable where the variable name is based on the current elements index and value is based on the text inside the element. 
        values[ 'child_' + (i+1) ] = value; // Optional****

        // Sums up all the values
        total += value;

    });

    // The optional lines enable you independently check each value, for example:
    // console.log( values.child_1 )

    // Push total into the #total element.
    $('#total').html( total );

}

total();

Here's an example where the values are updated with a click event. So what you do is just add the total() inside the click event as well.

function total() {

  var parentContainer = $('#mywraper'),
      total = 0;

  parentContainer.children().text(function( i, val ) {
    total += parseInt( val );
  });

  $('#total').html( total );

}

total();

$('#updateBtn').on("click", function() {

  $('#mywraper').children().text(function( i, val ) {
    return parseInt( val ) + 1;
  });

  total();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mywraper">
      <div>4</div>
      <div>5</div>
   <div>6</div>
</div>
<div id="total_div">
    Total $<span id="total"></span>
</div>

<button id="updateBtn">Update values</button>
Joonas
  • 7,227
  • 9
  • 40
  • 65