Hi there
In a cred-front-end-submission-form, how is it possible to calculate a value based on which terms have been checked in realtime and then save this value to a custom field?
Example:
1. User visits page "Create new ad"
2. The page "Create new ad" contains a CRED-submission-form.
3. User can choose between 1 or 10 regions, the ad will be shown. He chooses 3 regions (taxonomy terms).
4. At the same time, the custom field "Costs" shows the calculated value, e.g. "300$" (3 regions * 100$).
5. This all must happen in realtime via JS in order to let the user know about the actual prize ... maybe he thinks 300$ is too high and unchecks one region and so on...
Thanks for your help!
Regards
Philip
Dear Philip,
There are such built-in features within CRED form, and we can split your question into two parts:
Q1) client side: calculate a value based on which terms have been checked in realtime
This need custom JS codes, for example, you can setup a Javascript calculate the data when the user change some specific field value of CRED form:
hidden link
Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
and save the value into a hidden field,
hidden link
Q2) server side: save this value to a custom field?
You can use CRED action hook to cred_save_data to setup a custom PHP function, and save the value of hidden field into the database, see our document:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
Hi Luo
Thanks for your response. I reached out to a external developer in order to create such custom code and would like to share the result with you guys.
Thanks for all the help you're giving ... next question will be coming soon 🙂
Best
Philip
jQuery(document).ready(function(){
var valueMaps = {
1: '24',
2: '72',
3: '100',
4: '200'
}
function getTotalValues(hours) {
return parseInt(hours) * 10;
}
// "form_values_field" is the name of the class of the field that will show the calculated value
function setValues(values) {
jQuery('.form_values_field').val(values);
}
function calculateValues() {
var hours = jQuery('input[name=wpcf-input-radio-field-with-taxonomies]:checked').val();
var hourMapValue = valueMaps[hours];
var HourValues = getTotalValues(hourMapValue);
// you can calculate more values and add with total values
var anotherValue = 1;
var totalValues = parseInt(HourValues) + parseInt(anotherValue);
setValues(totalValues);
}
jQuery('input[name=wpcf-input-radio-field-with-taxonomies]').on('change', function(){
calculateValues()
});
calculateValues();
})