forked from wp-premium/gravityforms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconditional_logic.js
432 lines (329 loc) · 13 KB
/
conditional_logic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
var __gf_timeout_handle;
function gf_apply_rules(formId, fields, isInit){
var rule_applied = 0;
jQuery(document).trigger( 'gform_pre_conditional_logic', [ formId, fields, isInit ] );
for(var i=0; i < fields.length; i++){
gf_apply_field_rule(formId, fields[i], isInit, function(){
rule_applied++;
if(rule_applied == fields.length){
jQuery(document).trigger('gform_post_conditional_logic', [formId, fields, isInit]);
if(window["gformCalculateTotalPrice"])
window["gformCalculateTotalPrice"](formId);
}
});
}
}
function gf_check_field_rule(formId, fieldId, isInit, callback){
//if conditional logic is not specified for that field, it is supposed to be displayed
if(!window["gf_form_conditional_logic"] || !window["gf_form_conditional_logic"][formId] || !window["gf_form_conditional_logic"][formId]["logic"][fieldId])
return "show";
var conditionalLogic = window["gf_form_conditional_logic"][formId]["logic"][fieldId];
var action = gf_get_field_action(formId, conditionalLogic["section"]);
//If section is hidden, always hide field. If section is displayed, see if field is supposed to be displayed or hidden
if(action != "hide")
action = gf_get_field_action(formId, conditionalLogic["field"]);
return action;
}
function gf_apply_field_rule(formId, fieldId, isInit, callback){
var action = gf_check_field_rule(formId, fieldId, isInit, callback);
gf_do_field_action(formId, action, fieldId, isInit, callback);
var conditionalLogic = window["gf_form_conditional_logic"][formId]["logic"][fieldId];
//perform conditional logic for the next button
if(conditionalLogic["nextButton"]){
action = gf_get_field_action(formId, conditionalLogic["nextButton"]);
gf_do_next_button_action(formId, action, fieldId, isInit);
}
}
function gf_get_field_action(formId, conditionalLogic){
if(!conditionalLogic)
return "show";
var matches = 0;
for(var i = 0; i < conditionalLogic["rules"].length; i++){
var rule = conditionalLogic["rules"][i];
if(gf_is_match(formId, rule))
matches++;
}
var action;
if( (conditionalLogic["logicType"] == "all" && matches == conditionalLogic["rules"].length) || (conditionalLogic["logicType"] == "any" && matches > 0) )
action = conditionalLogic["actionType"];
else
action = conditionalLogic["actionType"] == "show" ? "hide" : "show";
return action;
}
function gf_is_match(formId, rule){
var isMatch = false;
var inputs = jQuery("#input_" + formId + "_" + rule["fieldId"] + " input");
var fieldValue;
if(inputs.length > 0){
//handling checkboxes/radio
for(var i=0; i< inputs.length; i++){
fieldValue = gf_get_value(jQuery(inputs[i]).val());
//find specific checkbox/radio item. Skip if this is not the specific item and the operator is not one that targets a range of values (i.e. greater than and less than)
var isRangeOperator = jQuery.inArray(rule["operator"], ["<", ">", "contains", "starts_with", "ends_with"]) >= 0;
if(fieldValue != rule["value"] && !isRangeOperator) {
continue;
}
//blank value if item isn't checked
if(!jQuery(inputs[i]).is(":checked")) {
fieldValue = "";
}
else if (fieldValue == "gf_other_choice"){
//get the value from the associated text box
fieldValue = jQuery("#input_" + formId + "_" + rule["fieldId"] + "_other").val();
}
if(gf_matches_operation(fieldValue, rule["value"], rule["operator"]))
isMatch = true;
}
}
else{
//handling all other fields (non-checkboxes)
var val = jQuery("#input_" + formId + "_" + rule["fieldId"]).val();
//transform regular value into array to support multi-select (which returns an array of selected items)
var values = (val instanceof Array) ? val : [val];
var matchCount = 0;
var fieldNumberFormat = window['gf_global'] && gf_global.number_formats && gf_global.number_formats[formId] && gf_global.number_formats[formId][rule["fieldId"]] ? gf_global.number_formats[formId][rule["fieldId"]] : false;
for(var i=0; i < values.length; i++){
//fields with pipes in the value will use the label for conditional logic comparison
var hasLabel = values[i] ? values[i].indexOf("|") >= 0 : true;
fieldValue = gf_get_value(values[i]);
var decimalSeparator = ".";
if( fieldNumberFormat && !hasLabel){
if( fieldNumberFormat == "currency" )
decimalSeparator = gformGetDecimalSeparator('currency');
else if( fieldNumberFormat == "decimal_comma")
decimalSeparator = ",";
else if( fieldNumberFormat == "decimal_dot")
decimalSeparator = ".";
//transform to a decimal dot number
fieldValue = gformCleanNumber( fieldValue, '', '', decimalSeparator);
//now transform to number specified by locale
if(window['gf_number_format'] && window['gf_number_format'] == "decimal_comma")
fieldValue = gformFormatNumber(fieldValue, -1, ",", ".");
if( ! fieldValue )
fieldValue = 0;
fieldValue = fieldValue.toString();
}
if(gf_matches_operation(fieldValue, rule["value"], rule["operator"])){
matchCount++;
}
}
//If operator is Is Not, none of the value can match
isMatch = rule["operator"] == "isnot" ? matchCount == values.length : matchCount > 0;
}
return gform.applyFilters( 'gform_is_value_match', isMatch, formId, rule );
}
function gf_try_convert_float(text){
var format = window["gf_number_format"] == "decimal_comma" ? "decimal_comma" : "decimal_dot";
if(gformIsNumeric(text, format)){
var decimal_separator = format == "decimal_comma" ? "," : ".";
return gformCleanNumber(text, "", "", decimal_separator);
}
return text;
}
function gf_matches_operation(val1, val2, operation){
val1 = val1 ? val1.toLowerCase() : "";
val2 = val2 ? val2.toLowerCase() : "";
switch(operation){
case "is" :
return val1 == val2;
break;
case "isnot" :
return val1 != val2;
break;
case ">" :
val1 = gf_try_convert_float(val1);
val2 = gf_try_convert_float(val2);
return gformIsNumber(val1) && gformIsNumber(val2) ? val1 > val2 : false;
break;
case "<" :
val1 = gf_try_convert_float(val1);
val2 = gf_try_convert_float(val2);
return gformIsNumber(val1) && gformIsNumber(val2) ? val1 < val2 : false;
break;
case "contains" :
return val1.indexOf(val2) >=0;
break;
case "starts_with" :
return val1.indexOf(val2) ==0;
break;
case "ends_with" :
var start = val1.length - val2.length;
if(start < 0)
return false;
var tail = val1.substring(start);
return val2 == tail;
break;
}
return false;
}
function gf_get_value(val){
if(!val)
return "";
val = val.split("|");
return val[0];
}
function gf_do_field_action(formId, action, fieldId, isInit, callback){
var conditional_logic = window["gf_form_conditional_logic"][formId];
var dependent_fields = conditional_logic["dependents"][fieldId];
for(var i=0; i < dependent_fields.length; i++){
var targetId = fieldId == 0 ? "#gform_submit_button_" + formId : "#field_" + formId + "_" + dependent_fields[i];
var defaultValues = conditional_logic["defaults"][dependent_fields[i]];
//calling callback function on the last dependent field, to make sure it is only called once
do_callback = (i+1) == dependent_fields.length ? callback : null;
gf_do_action(action, targetId, conditional_logic["animation"], defaultValues, isInit, do_callback);
gform.doAction('gform_post_conditional_logic_field_action', formId, action, targetId, defaultValues, isInit);
}
}
function gf_do_next_button_action(formId, action, fieldId, isInit){
var conditional_logic = window["gf_form_conditional_logic"][formId];
var targetId = "#gform_next_button_" + formId + "_" + fieldId;
gf_do_action(action, targetId, conditional_logic["animation"], null, isInit);
}
function gf_do_action(action, targetId, useAnimation, defaultValues, isInit, callback){
var $target = jQuery(targetId);
if(action == "show"){
// reset tabindex for selects
$target.find( 'select' ).each( function() {
$select = jQuery( this );
$select.attr( 'tabindex', $select.data( 'tabindex' ) );
} );
if(useAnimation && !isInit){
if($target.length > 0){
$target.slideDown(callback);
} else if(callback){
callback();
}
}
else{
var display = $target.data('gf_display');
//defaults to list-item if previous (saved) display isn't set for any reason
if ( display == '' || display == 'none' ){
display = 'list-item';
}
$target.css('display', display);
if(callback){
callback();
}
}
}
else{
//if field is not already hidden, reset its values to the default
var child = $target.children().first();
if (child.length > 0){
if(!gformIsHidden(child)){
gf_reset_to_default(targetId, defaultValues);
}
}
// remove tabindex and stash as a data attr for selects
$target.find( 'select' ).each( function() {
$select = jQuery( this );
$select.data( 'tabindex', $select.attr( 'tabindex' ) ).removeAttr( 'tabindex' );
} );
//Saving existing display so that it can be reset when showing the field
if( ! $target.data('gf_display') ){
$target.data('gf_display', $target.css('display'));
}
if(useAnimation && !isInit){
if($target.length > 0 && $target.is(":visible")) {
$target.slideUp(callback);
} else if(callback) {
callback();
}
} else{
$target.hide();
if(callback){
callback();
}
}
}
}
function gf_reset_to_default(targetId, defaultValue){
var dateFields = jQuery( targetId ).find( '.gfield_date_month input, .gfield_date_day input, .gfield_date_year input, .gfield_date_dropdown_month select, .gfield_date_dropdown_day select, .gfield_date_dropdown_year select' );
if( dateFields.length > 0 ) {
dateFields.each( function(){
var element = jQuery( this );
// defaultValue is associative array (i.e. [ m: 1, d: 13, y: 1987 ] )
if( defaultValue ) {
var key = 'd';
if (element.parents().hasClass('gfield_date_month') || element.parents().hasClass('gfield_date_dropdown_month') ){
key = 'm';
}
else if(element.parents().hasClass('gfield_date_year') || element.parents().hasClass('gfield_date_dropdown_year') ){
key = 'y';
}
val = defaultValue[ key ];
}
else{
val = "";
}
if(element.prop("tagName") == "SELECT" && val != '' )
val = parseInt(val);
if(element.val() != val)
element.val(val).trigger("change");
else
element.val(val);
});
return;
}
//cascading down conditional logic to children to suppport nested conditions
//text fields and drop downs, filter out list field text fields name with "_shim"
var target = jQuery(targetId).find('select, input[type="text"]:not([id*="_shim"]), input[type="number"], textarea');
var target_index = 0;
target.each(function(){
var val = "";
var element = jQuery(this);
//get name of previous input field to see if it is the radio button which goes with the "Other" text box
//otherwise field is populated with input field name
var radio_button_name = element.prev("input").attr("value");
if(radio_button_name == "gf_other_choice"){
val = element.attr("value");
}
else if(jQuery.isArray(defaultValue)){
val = defaultValue[target_index];
}
else if(jQuery.isPlainObject(defaultValue)){
val = defaultValue[element.attr("name")];
if( ! val ) {
// 'input_123_3_1' => '3.1'
var inputId = element.attr( 'id' ).split( '_' ).splice( -2 ).join( '.' );
val = defaultValue[ inputId ];
}
}
else if(defaultValue){
val = defaultValue;
}
if( element.is('select:not([multiple])') && ! val ) {
val = element.find( 'option' ).not( ':disabled' ).eq(0).val();
}
if(element.val() != val) {
element.val(val).trigger('change');
if (element.is('select') && element.next().hasClass('chosen-container')) {
element.trigger('chosen:updated');
}
}
else{
element.val(val);
}
target_index++;
});
//checkboxes and radio buttons
var elements = jQuery(targetId).find('input[type="radio"], input[type="checkbox"]:not(".copy_values_activated")');
elements.each(function(){
//is input currently checked?
var isChecked = jQuery(this).is(':checked') ? true : false;
//does input need to be marked as checked or unchecked?
var doCheck = defaultValue ? jQuery.inArray(jQuery(this).attr('id'), defaultValue) > -1 : false;
//if value changed, trigger click event
if(isChecked != doCheck){
//setting input as checked or unchecked appropriately
if(jQuery(this).attr("type") == "checkbox"){
jQuery(this).trigger('click');
}
else{
jQuery(this).prop("checked", doCheck);
//need to set the prop again after the click is triggered
jQuery(this).trigger('click').prop('checked', doCheck);
}
}
});
}