To create forms field that are calculated when other form fields are entered, you will need to do the following:
- Add classes to the form fields are that being used in the calculation
- Add custom JavaScript to the form to perform the calculation
There are many applications of this concept, here are a couple of examples:
Example 1: Subtraction calculation with two form fields
The following example shows how you could create a "Net Worth" Calculator using an ActiveDEMAND form.
This is how the form works:
- Enter total assets in form field
- Enter total liabilities in form field
- When the fields are entered, the net worth is automatically calculated (total assets - total liabilities)
Step 1: Add CSS classes to the form fields that are being used in the calculation
Step 2: Add a class to a text field that will be used to display the result of the calculation:
Step 3 (Optional): You can post the result of the calculation to a hidden field
Step 4: Add the following JavaScript code to the "Custom Script Tag" section of the form:
Result:
Example 2: Quote calculation using a fixed variable
The following example shows how you could generate a simple service quote:
This is how the form works:
- Enter number of hours in form field
- Cost per hour ($180) is hard coded in JavaScript
- When the form field is entered, the service quote is calculated (numbers of hours * 180)
Step 1: Add a CSS class to the form fields that is being used in the calculation
Step 2: Add a class to a text field that will be used to display the result of the calculation:
Step 3 (Optional): You can post the result of the calculation to a hidden field
Step 4: Add the following JavaScript code to "Custom Script Tag" section of the form:
<script type='text/javascript'>
/* only allow numbers to be entered */
$('%FORM.HTML_ID%').find(".hours").keydown(function(e){
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
/* do the calculation and output the results */
$('%FORM.HTML_ID%').find(".hours").keyup(function(){
var hours = parseInt($(this).val());
var estimate = (hours*180).toFixed(2);
$(".estimate").text("$" + estimate); $('%FORM.HTML_ID%').find("input[type=hidden]").val(estimate)
});
</script>
Result:
Comments
Please sign in to leave a comment.