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 find the HTML ID of the input fields. In this example, I’m using “Amount” and “Quantity” which id’s are fieldkOGQ3gQlnA and field_field_38

Finally, we’ll add the JavaScript Code to the JavaScript section of the page. (Make sure you remember to update fieldkOGQ3gQlnA and field_field_38 to your unique input values

var amountInputId = 'fieldkOGQ3gQlnA';
var quantityAmountId = 'field_field_38';
var inputsHaveLoaded = false;

function checkIfInputsHaveLoaded() {
    if(inputsHaveLoaded === false) {
        if ($('#'+quantityAmountId).html() !== undefined && $('#'+amountInputId).html() !== undefined) {
            inputsHaveLoaded = true;
        }
       window.setTimeout(checkIfInputsHaveLoaded, 100);
    } else {
        var calculateAndUpdateDom = function(){
            var amountInput = $('#'+amountInputId).val();
            var quantityAmount = $('#'+quantityAmountId).val();
            var calc = amountInput * quantityAmount;
            $('#total').html('$'+calc);
        };
        $('#'+amountInputId).keyup(function(){
            calculateAndUpdateDom();
        });
        $('#'+quantityAmountId).keyup(function(){
            calculateAndUpdateDom();
        });
    }
}
checkIfInputsHaveLoaded();

3 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?