Run basic math in real time on a form using JavaScript

Basic formulas work great but sometimes, you’ll want to display a simple calculation on the form in real-time.

Here’s an example of how this could look using some HTML inside a form and JavaScript. In the GIF below, we are multiplying Amount by Quantity and displaying the result above the save button.
2020-10-19_21-34-31

First, we’ll need to add the following to the HTML source code inside a Form Component

<p id="total">$0.00</p>

Next, you’ll need to add some classes to each field you would like to include in the calculation. For my example, I’ve added a class called “math-input” to both the Amount and Quantity and then a unique class “amount” and “quantity” for each field. So the CSS Class setting under Design for the Amount field is “math-input amount” and the Quantity field CSS Class setting is set to “math-input quantity” as shown in the image below.

Next, we need to find the Component ID since we are using the Tadabase JavaScript API. This can be found by hovering over the info icon in the Page Builder

Finally, we’ll add the JavaScript Code to the JavaScript section of the page. (Make sure you remember to update component_3, amount, quantity, total and math-input to your unique input values

TB.render('component_3',function(){
    var calculateAndUpdateDom = function(){
        var amountInput = $('.amount input').val();
        var quantityAmount = $('.quantity input').val();
        var calc = amountInput * quantityAmount;
        $('#total').html('$'+calc);
    };
    $('.math-input').keyup(function(){
        calculateAndUpdateDom();
    });
});

6 Likes

:grinning: Answers all kinds of questions.

Just saw this. Thanks, Moe. As @wescar says, this answers lots of questions.

I’m curious: If you store the field IDs, then the script won’t break if the field display names change, will it?

@Chem let me know if there’s a way to calculate in the Assigned Value from a Select field into this instant calculator. Thank you sir!

Hey @Eli

Here’s how that would look.
2021-04-27_9-25-37

You can follow all of the above steps except for the JavaScript code at the end.

Expand to view the first steps

The updated JavaScript for a Select field is as follows

TB.render('component_3',function(){
    function numberWithCommas(x) {
        var parts = x.toString().split(".");
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return parts.join(".");
    }
    var calculateAndUpdateDom = function(){
        var amountInput = $('.amount input').val();
        var quantityAmount = $('.quantity select').val();
        var calc = amountInput * quantityAmount;
        
        $('#total').html('$'+numberWithCommas(parseFloat(calc).toFixed(2)));
    };
    $('.math-input').on('keyup change', function(){
        calculateAndUpdateDom();
    });
});

Note: This can be done with a Select field that has Score Values assigned or a Select field that has numbers as options

1 Like

Amazing! Really appreciate the assist!

1 Like

Hi @Chem,
Thanks or the example.
I have a use case to use checkboxes.
For example, an ‘Include VAT’ checkbox that causes 20% to be added to the total.
Any chance you could expand your example to show how that could be achieved?

Thanks, Brett.

Hey @brettlewis, sure! So that would look like this.

Here are the expansion pack instructions.

  1. Add a Decision Box field and add the CSS Classes math-input include-vat

  2. Add the following to the code

     if($('.include-vat input')[0].checked){
         calc = calc * 1.2;
     }
    

So the result in my example looks like this.

TB.render('component_3',function(){
    var calculateAndUpdateDom = function(){
        var amountInput = $('.amount input').val();
        var quantityAmount = $('.quantity input').val();
        var calc = amountInput * quantityAmount;
        if($('.include-vat input')[0].checked){
            calc = calc * 1.2;
        }
        $('#total').html('$'+calc);
    };
    $('.math-input').on('keyup change',function(){
        calculateAndUpdateDom();
    });
});
2 Likes

Awesome, thanks, @chem. :slight_smile:

Much appreciated.

1 Like

If you’re looking for a way to do this with connected Number values, for example, a connected Number that will be the quantity, you can use the following.

You can follow all of the above steps except you’ll be adding a Connected Field and updating the JavaScript code at the end.

Here’s how it will look.

Expand to view the first steps

The updated JavaScript for a Connected field is as follows

TB.render('component_ID',function(){
    var calculateAndUpdateDom = function(){
        var amountInput = $('.amount input').val();
        var quantityAmount = $('.quantity af-data-table-field').html();
        var calc = amountInput * quantityAmount;
        $('#total').html('$'+calc);
    };
    $('.math-input').keyup(function(){
        calculateAndUpdateDom();
    }).bind('DOMSubtreeModified', function(){
      calculateAndUpdateDom();
    });
});

Note: If the connected value is a Currency field, you’ll need to update the 4th line to the following

var quantityAmount = $('.quantity af-data-table-field span').html();

1 Like

@Chem I am stuck here.
I try to read out a value of a date-field and then to add some time to it, and get it displayed on the form.

var dateInput = $(’.date-input input’).val();

Is that correct? Does the val() work, or do I need to initialize first the
var dateInput = new Date()

Thanks this is exactly what I needed and the examples work perfectly.

Hi all / @Chem Is it possible to place a calculated (calculated in realtime in the Javascript on the Form) value into a forms field value or straight into the records database it doesn’t necessarily have to be displayed on the form.

In this example I’m changing the quantity and the calculated value shown in blue is correct and should update the tables field.

Vidyard Recording?

Any pointers gratefully received
Thanks
Graham

Hey @GREDDIE,

Thanks for sending that video! I understand what you want, and it would be so cool to have, but at this time, you’ll need to submit the form to update the database fields.

okay thanks for confirming. I cut and paste the Javascript calculation in the form into a Pipe and then got a database rule to execute it. It means I’ve duplicated code but it’s working fine.

1 Like