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

Discussion

Discussion

Forms Table Calculations with Javascript

posted on October 20, 2017

I am trying to build a simple table that if the user enters any miles.  It multiplies that value by 0.535 and puts it into the Total field.

Otherwise the user can just input a value into the Total field if they don't need to input any miles.

Likewise I need to sum all the Total values into a Grand Total field outside of the Table.

Here is the table and Javascript I am trying to work with and the classes so you can see which fields I am trying to call in the Javascript.

 

$(document).ready(function () {
$('.cf-table-block').on('blur', 'input', sumtotal);

    
      function sumtotal() {
        var sum = 0;
        $('.cf-table-block tbody tr').each(function () {
            //Run if Miles field NOT Empty
          	if(($(this).find('.miles input').val() != ""){
                var s = 0;
                var miles = 0;
                var fueltotal = 0;
            	miles = parseNumber($(this).find('.miles input').val())
    			fueltotal = (miles * 0.535).toFixed(2);
    			s = $(this).find('.total input').val((fueltotal).toFixed(2));
                sum += s;
        	}
            //Run if Miles Empty                               
            else{
				var s = 0;
                s = $(this).find('.total input').val();                           
                sum += s;                           
            }                                 
       });

       $('.grandtotal input').val((sum).toFixed(2));
    }
  
  
function parseNumber(n) {
	var f = parseFloat(n); //Convert to float number.
	return isNaN(f) ? alert('Not Float') : f; //treat invalid input as 0;
}
  
  
});
  

 

0 0
replied on October 23, 2017 Show version history

hello chase,

 

why don't you use the embedded formulas that forms provides without coding ?

it is very simple and easy:

1- for the total field in the table, go to fields option and go to advanced and put your calculation there by using excel like formulas

for your case it will look something like this in the formula write :

=INDEX(table.Miles, ROW())* 0.535

 make sure that MILES field is NUMBER field, if it is single line, you should put

=INDEX(VALUE(table.MILES,ROW())*0.535

assuming that "table" is the variable name for the table

2- for the grand total, go to the grand total field and go to andvanced, and write there :

if number

=SUM(table.Miles)

if single line

 =SUM(VALUES(tables.MILES)

, if it doesnt work for single line at all, then replace the single lines with number fields.

 

Hope this will do,

Maher.

 

 

 

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

Sign in to reply to this post.