You are viewing limited content. For full access, please sign in.

Question

Question

how to subtract numbers within a table to calculate a balance

asked on September 15, 2016 Show version history

Hi all,

my intention is to calculate a leave balance based on a type from a dropdown list by subtracting the "number of days" from the "total leave balance", which would give me the new balance.

The calculation works perfectly for the first row , but when a new row is added, it still subtracts the "number of days" from the first row selection.

This is what is currently does:

here is my code:

$(document).ready(function(){

   $('.cf-table tbody').on('change','.dropdown', function(){
   
      switch ($(this).find(':selected').val()){
   
      case 'Annual':
      var a = parseNumberA($('.annual input').val())-parseNumberA($('.days input').val());
      $('.newA input').val(a);
      function parseNumberA(a)
      {
      var f = parseFloat(a); 
      return isNaN(f) ? 0 : f; 
      }
      break;
          
      case 'Sick':
      var s = parseNumberS($('.sick input').val())-parseNumberS($('.days input').val());
      $('.newS input').val(s);   
      function parseNumberS(s)
      {
      var g = parseFloat(s); 
      return isNaN(g) ? 0 : g; 
      }
      break;
      case 'Family Responsibility':
      var r = parseNumberF($('.family input').val())-parseNumberF($('.days input').val());
      $('.newF input').val(r);   
      function parseNumberF(r)
      {
      var h = parseFloat(r); 
      return isNaN(h) ? 0 : h; 
      }
      break;
      default:
      $('.new input').val();
      break;
         
    }
 });
});

Any help would be appreciated.

0 0

Replies

replied on September 15, 2016 Show version history

Your code for $('.days input').val() always returns the val for the first matching item, which is the first row. What you need to do is get all rows that match the row that is changing, and then add their values, and subtract that from the total.

 

This might not be perfect, but hopefully it helps.

$('.cf-table tbody').on('change','.dropdown', function(){
      var selected = $(this).find(':selected').val();
	  var total = 0;
   //for every row, filter based on the dropdown being equal to
   //the selected value from the new item, then for each match
   //add them to the total
	  $('.cf-table tbody tr').filter(function(){
		  return $(this).find('.dropdown:selected').val()==selected;
	  }).each(function(){
		  var val = $(this).find('.days').val();
		  total += $.isNumeric(val) ? parseFloat(val) : 0;
	  });
	  
	  switch(selected){
		case 'Annual':
		  $('.newA input').val(parseFloat($('.annual input').val() - total);
		  break;
		case 'Sick':
		  $('.newS input').val(parseFloat($('.sick input').val() - total);
		  break;
		case 'Family Responsibility':
		  $('.newF input').val(parseFloat($('.family input').val() - total);
		  break;
	  }

 

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.