Is it possible in forms to create an online calculated field?
Hi,
We are looking to have a simple online form, with 2 numeric fields (e.g. price and quantity), where we have 3rd field that displays the multiplication of the first 2 fields, and is being re-calculated once each of the first 2 fields change.
To be clear we would like the 3rd field to show the correct result, before the form is submitted.
How can we perform this? Is there a JavaScript hook we can use?
Is it possible in forms to create an online calculated field?
I would probably create an HTML form and then use JavaScript to calculate the total and submit the form to HubSpot.
This is a fairly rough example so it will need some tweaking, but your HTML can be something like this:
<form name="totalCalculator" id="totalCalculator" action="https://forms.hubspot.com/uploads/form/v2/[[ your_portal_id ]]/[[ your_form_id ]]" method="post">
<input type="text" id="firstname" name="firstname" placeholder="Your First Name">
<input type="text" id="lastname" name="lastname" placeholder="Your Last Name">
<input type="text" id="email" name="email" placeholder="Your Email Address">
<input type="price" id="price" name="price">
<input type="quantity" id="quantity" name="quantity">
<div class="total">
Your total will be <span id="total"></span>
</div>
<button id="calculate">Calculate</button>
</form>
And your JavaScript something like this:
function calculate() {
var price = document.querySelector('#totalCalculator input[name="price"]').value;
var quantity = document.querySelector('#totalCalculator input[name="price"]').value;
var totalField = document.querySelector('span#total');
var total = price * quantity;
totalField.textContent = total;
}
var calculateButton = document.querySelector('#calculate');
calculateButton.addEventListener('click', function(){
var form = document.querySelector('#totalCalculator');
calculate();
form.submit();
}, false);
That should both calculate the amount and populate the #total span with the value and submit the form. You'll want the input name values to match up to the property's internal name on HubSpot.
EDIT: To answer the hook question, there are also some events that you can use here.
I might just be looking way to far into this…but what do you think about separating the calculation from the submition? Given the usecase that the user might want to see the calculation before submission.
Edit: Step was added, assuming we would be working in US dollars.
Maybe something like this:
Markup
<form name="totalCalculator" id="totalCalculator" action="https://forms.hubspot.com/uploads/form/v2/[[ your_portal_id ]]/[[ your_form_id ]]" method="post">
<input id="price" name="price" type="number" step=".01">
<input id="quantity" name="quantity" type="number" step=".01">
<input id="total" name="total" type="number" step=".01">
<div class="total">
Your total will be <span id="total"></span>
</div>
<button id="calculate">Submit</button>
</form>