Run Basic Math in Real Time on a Form
Please note that this is now available as a plugin for easier installation. While you can use this document as a reference, the recommended method to add this functionality is through the plugin installation wizard. Learn more about plugins here.
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 our custom code features. In the GIF below, we multiply Amount by Quantity and display the result above the save button.
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 a class to each field you would like to include in the calculation.
Here, I’ve added a class called “math-input” to both the Amount and Quantity and then unique classes of “amount” and “quantity” for each field. The Amount field would read “math-input amount” and the Quantity field “math-input quantity,” as shown in the image below.
Next, we need to find the Component ID. This can be found by hovering over the info icon in the Page Builder.
Finally, we’ll add the JavaScript Code to the JavaScript tab of the page.
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();
});
});
We'd love to hear your feedback.