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

Question

Question

Form Javascript subtracting field values.

asked on July 13, 2016 Show version history

This is the form.  I am wanting to subtract the Balance value from the Grand Total to give me a Balance Remaining. 

$(document).ready(function () {
    $('.cf-table-block').on('blur', 'input', sumtotal);
    $('.subtotal').on('blur', 'input', sumtotal)
    $('.quantity').on('blur', 'input', sumtotal);
    function sumtotal() {
        var sum = 0;
        $('.cf-table-block tbody tr').each(function () {
            var s = 0;
            s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
            $(this).find('.subtotal input').val(s);
            sum += s;            
        });
      	$('.total input').val(sum.toFixed(2));      
    }
  	
    $('balance input, total input').blur(function () {
    $('#remaining input').val($('#balance input').val() - $('total input').val());
    }); 		
  
    function parseNumber(n) {
        var f = parseFloat(n); //Convert to float number.
        return isNaN(f) ? 0 : f; //treat invalid input as 0;
    }
});

balance is the class given to the field Balance

total is the class given to the field Grand Total which it's value is the result of the table calculations.

remaining is the class given to the field Balance Remaining

 

The Balance value is loaded from a database via Lookup.

0 0

Replies

replied on July 13, 2016

Looks like your code to do the subtraction has a few errors. When referencing CSS classes in a selector, you use a "." prefix. Also, you probably want to wrap the field values in a call to your parseNumber function to prevent issues with variable type ambiguity.

 

$('.balance input, .total input').blur(function () {
  $('.remaining input').val(parseNumber($('.balance input').val()) - parseNumber($('.total input').val()));
}); 	

 

0 0
replied on January 3, 2017

How do you change the code to restrict the values to two decimals?

0 0
replied on January 19, 2017

I would use the toFixed() function. You apply it to a number and specify how many decimal places to keep, like "number.toFixed(2)" as an example. To modify the code above, it would be:

$('.balance input, .total input').blur(function () {
  $('.remaining input').val((parseNumber($('.balance input').val()) - parseNumber($('.total input').val())).toFixed(2));
}); 	

 

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

Sign in to reply to this post.