skip to Main Content

EDIT (using only jQuery)

I changed the code based on the comments so I don’t need a form.
I’m not the greatest in coding, but I try. When I use the code below <div class="td3-title" id="result_in"></div> doesn’t show a number (it’s empty).

<div class="td2">1</div> will later be a calculation for the percentages, but that’s for later.

What I want to achieve is:

  • auto calculate the fields
  • adding extra fields and the script should be able to calculate the extra fields also (add it to the jQuery-code)
  • everything should happen on page (not sending data to a server)
<script>
$("#in1").keyup(calc);
$("#in2").keyup(calc);

function calc() {

    $('#result_in').html(
        parseFloat($('#in1').val(), 10) + parseFloat($("#in2").val(), 10 + parseFloat($("#in3").val(), 10)
    );
}
</script>

<script>
$(function ($) {

    $('body').on("click", '#addFieldsIn', function () {
        $('#table-in').append('<div class="tr"><div class="td1"><input type="text" placeholder="Change description" value=""></div><div class="td2">1</div><div class="td3"><input type="number" id="in1" placeholder="0" value=""></div></div>')
    })

})(jQuery)
</script>
<div id="table-in">
    <div class="tr">
        <div class="td1-title">In</div>
        <div class="td2-title">%</div>
        <div class="td3-title">&euro;</div>
    </div>
    <div class="tr">
        <div class="td1"><input type="text" placeholder="Change description" value=""></div>
        <div class="td2">1</div>
        <div class="td3"><input type="number" id="in1" placeholder="0" value=""></div>
    </div>
    <div class="tr">
        <div class="td1"><input type="text" placeholder="Change description" value=""></div>
        <div class="td2">1</div>
        <div class="td3"><input type="number" id="in2" placeholder="0" value=""></div>
    </div>
    <div class="tr">
        <div class="td1"><input type="text" placeholder="Change description" value=""></div>
        <div class="td2">1</div>
        <div class="td3"><input type="number" id="in3" placeholder="0" value=""></div>
    </div>
</div>
<div id="tableEnd">
    <div class="tr">
        <div class="td1"><button id="addFieldsIn">+ Add field</button></div>
        <div class="td2"></div>
        <div class="td3"></div>
    </div>
    <div class="tr">
        <div class="td1-title">Total in</div>
        <div class="td2-title">1</div>
        <div class="td3-title" id="result_in"></div>
    </div>
</div>

**

EDIT jQuery

I tried to combine multiple functions, but it breaks the calculations for var totalIn. What do I do wrong?

<script>
$(document).ready(function() {
  calc(); //call function to calculate
  $('body').on("click", '#addFieldsIn', function() {
    $('#table-in').append('<div class="tr"><div class="td1"><input type="text" placeholder="Change description"></div><div class="td2">1</div><div class="td3"><input type="number" placeholder="0"></div></div>')
    calc(); //if passing any default value in input box 
  })
  
  $('body').on("click", '#addFieldsOut', function() {
    $('#table-out').append('<div class="tr"><div class="td1"><input type="text" placeholder="Change description"></div><div class="td2">1</div><div class="td3"><input type="number" placeholder="0"></div></div>')
    calc(); //if passing any default value in input box 
  })

  $('body').on("keyup", '.td3 > input', function() {
    calc(); //when value keyup in input box
  })

  function calc() {
    var totalIn = 0; //for storing overall total
    $("#table-in .td3 > input").each(function() {
      totalIn += ($(this).val()) ? parseFloat($(this).val()) : 0; //further can format to parsefloat if needed or add more checks
    })
    $('#result_in').text(totalIn);
  }
  
  function calc() {
    var totalOut = 0; //for storing overall total
    $("#table-out .td3 > input").each(function() {
      totalOut += ($(this).val()) ? parseFloat($(this).val()) : 0; //further can format to parsefloat if needed or add more checks
    })
    $('#result_out').text(totalOut);
  }
})
</script>

**

2

Answers


  1. Override the default submit function with Javascript and manually post the form using Ajax

    In the example I gave, I presumed you have the form an ID <form id="theform">

    $("#theform").submit(function(e){
      // don't do the default action
      e.preventDefault();
    
      submitData = $(this).serialize();
    
      $.ajax({
        method: 'post',
        url: '',
        data: submitData,
        success: function(data){
          // Show feedback that the form was saved submitted
        },
      });
    });
    

    Edit

    I feel like this issue went into a completely different direction Lol.

    But this is for your most recent edit.
    you can’t have two functions with the same name, so break them up.

    Basic example

    function calc_in() {
      var totalIn = 0; //for storing overall total
      $("#table-in .td3 > input").each(function() {
        totalIn += ($(this).val()) ? parseFloat($(this).val()) : 0; //further can format to parsefloat if needed or add more checks
      })
      $('#result_in').text(totalIn);
    };
    
    function calc_out() {
      var totalOut = 0; //for storing overall total
      $("#table-out .td3 > input").each(function() {
        totalOut += ($(this).val()) ? parseFloat($(this).val()) : 0; //further can format to parsefloat if needed or add more checks
      })
      $('#result_out').text(totalOut);
    };
    function calc(){
      calc_out();
      calc_in();
    };
    

    Somewhat Optimized version (2 instead of 1)

    function calc_table(targetTable, targetResult) {
      var total = 0; //for storing overall total
      $(targetTable).find('.td3 > input').each(function() {
        total += ($(this).val()) ? parseFloat($(this).val()) : 0; //further can format to parsefloat if needed or add more checks
      })
      $(targetResult).text(total);
    };
    
    function calc(){
      $.each(['in', 'out'], function(i, t){ // t - for target
        calc_table($('#table-'+t), $('#result_'+t));
      });
    };
    

    But the rest seems to work, I tested it locally..
    if your still having issues with NaN you could do: (isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val())); as an alternative


    and I’d recommend placing the functions right above $(document).ready( so that they’re Global functions.

    • You can call them manually in the Console (for testing)
    • In general the function should be above where it’s being called (this is for all languages, good habit to get into)
    Login or Signup to reply.
  2. You can iterate through your .tr then inside div get the value of input box and on each iteration add the sum of the value in any variable and assign it to your result_in div.

    Demo Code :

    $(document).ready(function() {
      calc(); //call fnction to calculate
      $('body').on("click", '#addFieldsIn', function() {
        $('#table-in').append('<div class="tr"><div class="td1"><input type="text" placeholder="Change description" value=""></div><div class="td2">1</div><div class="td3"><input type="number" placeholder="0" value=""></div></div>')
        calc(); //if passing any default value in input box 
      })
    
      $('body').on("change", '.td3 > input', function() {
        calc(); //when value change in input box
      })
    
      function calc() {
        var total = 0; //for storing overall total
        $("#table-in .td3 > input").each(function() {
          total += ($(this).val()) ? parseInt($(this).val()) : 0; //further can format to parsefloat if needed or add more checks
        })
        $('#result_in').text(total);
      }
    })
    #table-in>.tr {
      border: 1px solid black;
    }
    
    #result_in {
      color: red;
    }
    
    #table-in {
      display: table-row-group;
    }
    
    .tr {
      display: table-row;
    }
    
    .td1,
    .td2,
    .td3 {
      display: table-cell;
      border: 1px solid #dddddd;
      padding: 8px;
      line-height: 1.42857143;
      vertical-align: top;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="table-in">
      <div class="tr">
        <div class="td1">In</div>
        <div class="td2">&#x25;</div>
        <div class="td3">&euro;</div>
      </div>
      <div class="tr">
        <div class="td1"><input type="text" placeholder="Change description" value=""></div>
        <div class="td2">1</div>
        <div class="td3"><input type="number" id="in1" placeholder="0" value=""></div>
      </div>
      <div class="tr">
        <div class="td1"><input type="text" placeholder="Change description" value=""></div>
        <div class="td2">1</div>
        <div class="td3"><input type="number" id="in3" placeholder="0" value=""></div>
      </div>
    </div>
    <div class="tr">
      <div class="td1">Total in</div>
      <div class="td2">1</div>
      <div class="td3" id="result_in"></div>
    </div>
    <div class="tr">
      <div class="td1"><button id="addFieldsIn">+ Add field</button></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search