Skip to content

Instantly share code, notes, and snippets.

@alfredo-wpmudev
Last active December 22, 2021 02:17
Show Gist options
  • Save alfredo-wpmudev/a9c5e783b4fca1d00ff4f91dcd2dbef5 to your computer and use it in GitHub Desktop.
Save alfredo-wpmudev/a9c5e783b4fca1d00ff4f91dcd2dbef5 to your computer and use it in GitHub Desktop.
<?php
/* Inline script printed out in the footer */
add_action('wp_footer', 'forminator_conditional_calculation_script_wp_footer');
function forminator_conditional_calculation_script_wp_footer() {
?>
<script>
//Demo -> https://cuban.tempurl.host/forminator-if-conditional/
//Checking if the forminator form [forminator_form id="1046668"] exist on the page
if(jQuery("#forminator-module-1046668")){
/* In this example the calculation is {hidden-1}*{number-1}*{number-2} */
/*Use HTML field to show the Price Value({hidden-1}) */
//It need the field subject to the conditions be part of the form in this case {hidden-1}
//This field need to be hidden
var priceField = jQuery("#hidden-1");
//A variable to hold the original price value,
var frmPrice = 15; //Need to be here to avoid cache/cookies issues
//The field that trigger the condition (Usually the same on the condition, but you can use as many you wich)
var totalPersonField = jQuery("#forminator-field-number-1");
//For every field involded on the conditional need to trigger the onChange event with the custom function applyDiscount
totalPersonField.change(applyDiscountForm1046668);
//applyDiscount is the logic of the conditional
function applyDiscountForm1046668(){
//Local variable to get the value of the field in the condition, create as many field involved
let total_person = totalPersonField.val();
//Conditions to apply the discount
//Javascript If/Else ---> https://www.w3schools.com/js/js_if_else.asp
//Javascript Comparisson ---> https://www.w3schools.com/js/js_comparisons.asp
if(total_person >= 2 && total_person <= 9){
//If the total of persons is > 1 will apply a 10% discount, simpele way to do it price*90/100 = price*0.9
priceField.val(frmPrice*0.9);
}
else if(total_person >= 10 && total_person <= 15){
//20% discount
priceField.val(frmPrice*0.8);
}
else if(total_person >= 16 && total_person <= 20){
//30% discount
priceField.val(frmPrice*0.7);
}
else if(total_person >= 21 && total_person <= 39){
//40% discount
priceField.val(frmPrice*0.6);
}
else if(total_person >= 40){
//50% discount
priceField.val(frmPrice*0.5);
}
else{
//If none of the condition apply use the original price set on the form
priceField.val(frmPrice);
}
}
}
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment