PluginProbe ʕ •ᴥ•ʔ
Conditional Fields for Contact Form 7 / 2.0.1
Conditional Fields for Contact Form 7 v2.0.1
2.7.9 2.7.8 2.7.7 2.7.6 2.7.5 2.7.4 2.7.3 2.7.2 0.2.4 0.2.5 0.2.6 0.2.7 0.2.8 0.2.9 1.0 1.1 1.2 1.2.1 1.2.2 1.2.3 1.3 1.3.1 1.3.2 1.3.3 1.3.4 1.4 1.4.1 1.4.2 1.4.3 1.5 1.5.1 1.5.2 1.5.3 1.5.4 1.5.5 1.6.1 1.6.2 1.6.3 1.6.5 1.7 1.7.1 1.7.2 1.7.3 1.7.4 1.7.5 1.7.6 1.7.8 1.7.9 1.8 1.8.1 1.8.2 1.8.3 1.8.5 1.8.6 1.8.7 1.9 1.9.1 1.9.10 1.9.11 1.9.12 1.9.13 1.9.14 1.9.15 1.9.16 1.9.2 1.9.3 1.9.4 1.9.5 1.9.6 1.9.7 1.9.8 1.9.9 2.0 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.0.7 2.0.8 2.0.9 2.1 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.1.6 2.2 2.2.1 2.2.10 2.2.11 2.2.2 2.2.3 2.2.4 2.2.5 2.2.6 2.2.7 2.2.8 2.2.9 2.3 2.3.1 2.3.10 2.3.11 2.3.12 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.3.7 2.3.8 2.3.9 2.4 2.4.1 2.4.10 2.4.11 2.4.12 2.4.13 2.4.14 2.4.15 2.4.2 2.4.3 2.4.4 2.4.5 2.4.6 2.4.7 2.4.8 2.4.9 2.5 2.5.1 2.5.10 2.5.11 2.5.12 2.5.13 2.5.14 2.5.2 2.5.3 2.5.4 2.5.5 2.5.6 2.5.7 2.5.8 2.5.9 2.6 2.6.1 2.6.2 2.6.3 2.6.4 2.6.5 2.6.6 2.6.7 2.6.8 2.7 2.7.1 trunk 0.1 0.1.1 0.1.2 0.1.3 0.1.4 0.1.5 0.1.6 0.1.7 0.2 0.2.1 0.2.2 0.2.3
cf7-conditional-fields / js / scripts_es6.js
cf7-conditional-fields / js Last commit date
scripts.js 5 years ago scripts.js.map 5 years ago scripts_admin.js 5 years ago scripts_admin_all_pages.js 5 years ago scripts_es6.js 5 years ago
scripts_es6.js
1530 lines
1 "use strict";
2
3 var cf7signature_resized = 0; // for compatibility with contact-form-7-signature-addon
4
5 var wpcf7cf_timeout;
6 var wpcf7cf_change_time_ms = 100;
7
8 if (window.wpcf7 && !wpcf7.setStatus) {
9 wpcf7.setStatus = ( form, status ) => {
10 form = form.length ? form[0] : form; // if form is a jQuery object, only grab te html-element
11 const defaultStatuses = new Map( [
12 // 0: Status in API response, 1: Status in HTML class
13 [ 'init', 'init' ],
14 [ 'validation_failed', 'invalid' ],
15 [ 'acceptance_missing', 'unaccepted' ],
16 [ 'spam', 'spam' ],
17 [ 'aborted', 'aborted' ],
18 [ 'mail_sent', 'sent' ],
19 [ 'mail_failed', 'failed' ],
20 [ 'submitting', 'submitting' ],
21 [ 'resetting', 'resetting' ],
22 ] );
23
24 if ( defaultStatuses.has( status ) ) {
25 status = defaultStatuses.get( status );
26 }
27
28 if ( ! Array.from( defaultStatuses.values() ).includes( status ) ) {
29 status = status.replace( /[^0-9a-z]+/i, ' ' ).trim();
30 status = status.replace( /\s+/, '-' );
31 status = `custom-${ status }`;
32 }
33
34 const prevStatus = form.getAttribute( 'data-status' );
35
36 form.wpcf7.status = status;
37 form.setAttribute( 'data-status', status );
38 form.classList.add( status );
39
40 if ( prevStatus && prevStatus !== status ) {
41 form.classList.remove( prevStatus );
42 }
43
44 return status;
45 };
46 }
47
48 if (window.wpcf7cf_running_tests) {
49 jQuery('input[name="_wpcf7cf_options"]').each(function(e) {
50 var $input = jQuery(this);
51 var opt = JSON.parse($input.val());
52 opt.settings.animation_intime = 0;
53 opt.settings.animation_outtime = 0;
54 $input.val(JSON.stringify(opt));
55 });
56 wpcf7cf_change_time_ms = 0;
57 }
58
59 var wpcf7cf_show_animation = { "height": "show", "marginTop": "show", "marginBottom": "show", "paddingTop": "show", "paddingBottom": "show" };
60 var wpcf7cf_hide_animation = { "height": "hide", "marginTop": "hide", "marginBottom": "hide", "paddingTop": "hide", "paddingBottom": "hide" };
61
62 var wpcf7cf_show_step_animation = { "opacity": "show" };
63 var wpcf7cf_hide_step_animation = { "opacity": "hide" };
64
65 var wpcf7cf_change_events = 'input.wpcf7cf paste.wpcf7cf change.wpcf7cf click.wpcf7cf propertychange.wpcf7cf';
66
67 var wpcf7cf_forms = [];
68
69 window.wpcf7cf_dom = {};
70
71 const wpcf7cf_reload_dom = function($form) {
72 wpcf7cf_dom = wpcf7cf.get_simplified_dom_model($form[0]);
73 }
74
75 const wpcf7cf_getFieldsByOriginalName = function(originalName) {
76 return Object.values(wpcf7cf_dom).filter(function (inputField) {
77 return inputField.original_name === originalName || inputField.original_name === originalName+'[]';
78 });
79 }
80
81 const wpcf7cf_getFieldByName = function(name) {
82 return wpcf7cf_dom[name] || wpcf7cf_dom[name+'[]'];
83 }
84
85 // endsWith polyfill
86 if (!String.prototype.endsWith) {
87 String.prototype.endsWith = function(search, this_len) {
88 if (this_len === undefined || this_len > this.length) {
89 this_len = this.length;
90 }
91 return this.substring(this_len - search.length, this_len) === search;
92 };
93 }
94
95 // Object.values polyfill
96 if (!Object.values) Object.values = o=>Object.keys(o).map(k=>o[k]);
97
98 // Array.from polyfill
99 if (!Array.from) {
100 Array.from = (function () {
101 var toStr = Object.prototype.toString;
102 var isCallable = function (fn) {
103 return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
104 };
105 var toInteger = function (value) {
106 var number = Number(value);
107 if (isNaN(number)) { return 0; }
108 if (number === 0 || !isFinite(number)) { return number; }
109 return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
110 };
111 var maxSafeInteger = Math.pow(2, 53) - 1;
112 var toLength = function (value) {
113 var len = toInteger(value);
114 return Math.min(Math.max(len, 0), maxSafeInteger);
115 };
116
117 // The length property of the from method is 1.
118 return function from(arrayLike/*, mapFn, thisArg */) {
119 // 1. Let C be the this value.
120 var C = this;
121
122 // 2. Let items be ToObject(arrayLike).
123 var items = Object(arrayLike);
124
125 // 3. ReturnIfAbrupt(items).
126 if (arrayLike == null) {
127 throw new TypeError("Array.from requires an array-like object - not null or undefined");
128 }
129
130 // 4. If mapfn is undefined, then let mapping be false.
131 var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
132 var T;
133 if (typeof mapFn !== 'undefined') {
134 // 5. else
135 // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
136 if (!isCallable(mapFn)) {
137 throw new TypeError('Array.from: when provided, the second argument must be a function');
138 }
139
140 // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
141 if (arguments.length > 2) {
142 T = arguments[2];
143 }
144 }
145
146 // 10. Let lenValue be Get(items, "length").
147 // 11. Let len be ToLength(lenValue).
148 var len = toLength(items.length);
149
150 // 13. If IsConstructor(C) is true, then
151 // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
152 // 14. a. Else, Let A be ArrayCreate(len).
153 var A = isCallable(C) ? Object(new C(len)) : new Array(len);
154
155 // 16. Let k be 0.
156 var k = 0;
157 // 17. Repeat, while k < len… (also steps a - h)
158 var kValue;
159 while (k < len) {
160 kValue = items[k];
161 if (mapFn) {
162 A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
163 } else {
164 A[k] = kValue;
165 }
166 k += 1;
167 }
168 // 18. Let putStatus be Put(A, "length", len, true).
169 A.length = len;
170 // 20. Return A.
171 return A;
172 };
173 }());
174 }
175
176 var Wpcf7cfForm = function($form) {
177
178 var options_element = $form.find('input[name="_wpcf7cf_options"]').eq(0);
179 if (!options_element.length || !options_element.val()) {
180 // doesn't look like a CF7 form created with conditional fields plugin enabled.
181 return false;
182 }
183
184 var form = this;
185
186 var form_options = JSON.parse(options_element.val());
187
188 form.$form = $form;
189 form.$input_hidden_group_fields = $form.find('[name="_wpcf7cf_hidden_group_fields"]');
190 form.$input_hidden_groups = $form.find('[name="_wpcf7cf_hidden_groups"]');
191 form.$input_visible_groups = $form.find('[name="_wpcf7cf_visible_groups"]');
192 form.$input_repeaters = $form.find('[name="_wpcf7cf_repeaters"]');
193 form.$input_steps = $form.find('[name="_wpcf7cf_steps"]');
194
195 form.unit_tag = $form.closest('.wpcf7').attr('id');
196 form.conditions = form_options['conditions'];
197
198 // Wrapper around jQuery(selector, form.$form)
199 form.get = function (selector) {
200 // TODO: implement some caching here.
201 return jQuery(selector, form.$form);
202 }
203
204 // compatibility with conditional forms created with older versions of the plugin ( < 1.4 )
205 for (var i=0; i < form.conditions.length; i++) {
206 var condition = form.conditions[i];
207 if (!('and_rules' in condition)) {
208 condition.and_rules = [{'if_field':condition.if_field,'if_value':condition.if_value,'operator':condition.operator}];
209 }
210 }
211
212 form.initial_conditions = form.conditions;
213 form.settings = form_options['settings'];
214
215 form.$groups = jQuery(); // empty jQuery set
216 form.repeaters = [];
217 form.multistep = null;
218 form.fields = [];
219
220 form.settings.animation_intime = parseInt(form.settings.animation_intime);
221 form.settings.animation_outtime = parseInt(form.settings.animation_outtime);
222
223 if (form.settings.animation === 'no') {
224 form.settings.animation_intime = 0;
225 form.settings.animation_outtime = 0;
226 }
227
228 form.updateGroups();
229 form.updateEventListeners();
230 form.displayFields();
231
232 // bring form in initial state if the reset event is fired on it.
233 form.$form.on('reset.wpcf7cf', form, function(e) {
234 var form = e.data;
235 setTimeout(function(){
236 form.displayFields();
237 form.resetRepeaters();
238 if (form.multistep != null) {
239 form.multistep.moveToStep(1);
240 }
241 },200);
242 });
243
244 // PRO ONLY
245
246 form.get('.wpcf7cf_repeater:not(.wpcf7cf_repeater .wpcf7cf_repeater)').each(function(){
247 form.repeaters.push(new Wpcf7cfRepeater(jQuery(this),form));
248 });
249
250 form.$input_repeaters.val(JSON.stringify(form.repeaters.map((item)=>item.params.$repeater.id)));
251
252 var $multistep = form.get('.wpcf7cf_multistep');
253
254 if ($multistep.length) {
255 form.multistep = new Wpcf7cfMultistep($multistep, form);
256 // window.wpcf7cf.updateMultistepState(form.multistep);
257 }
258
259 // END PRO ONLY
260
261 }
262
263 /**
264 * reset initial number of subs for each repeater.
265 * (does not clear values)
266 */
267 Wpcf7cfForm.prototype.resetRepeaters = function() {
268 var form = this;
269 form.repeaters.forEach(repeater => {
270 repeater.updateSubs( repeater.params.$repeater.initial_subs );
271 });
272 }
273
274 Wpcf7cfForm.prototype.displayFields = function() {
275
276 var form = this;
277
278 var wpcf7cf_conditions = this.conditions;
279 var wpcf7cf_settings = this.settings;
280
281 //for compatibility with contact-form-7-signature-addon
282 if (cf7signature_resized === 0 && typeof signatures !== 'undefined' && signatures.constructor === Array && signatures.length > 0 ) {
283 for (var i = 0; i < signatures.length; i++) {
284 if (signatures[i].canvas.width === 0) {
285
286 var $sig_canvas = jQuery(".wpcf7-form-control-signature-body>canvas");
287 var $sig_wrap = jQuery(".wpcf7-form-control-signature-wrap");
288 $sig_canvas.eq(i).attr('width', $sig_wrap.width());
289 $sig_canvas.eq(i).attr('height', $sig_wrap.height());
290
291 cf7signature_resized = 1;
292 }
293 }
294 }
295
296 form.$groups.addClass('wpcf7cf-hidden');
297
298 wpcf7cf_reload_dom(form.$form);
299
300 for (var i=0; i < wpcf7cf_conditions.length; i++) {
301
302 var condition = wpcf7cf_conditions[i];
303
304 var show_group = window.wpcf7cf.should_group_be_shown(condition, form);
305
306 if (show_group) {
307 form.get('[data-id="'+condition.then_field+'"]').removeClass('wpcf7cf-hidden');
308 }
309 }
310
311
312 var animation_intime = wpcf7cf_settings.animation_intime;
313 var animation_outtime = wpcf7cf_settings.animation_outtime;
314
315 form.$groups.each(function (index) {
316 var $group = jQuery(this);
317 if ($group.is(':animated')) {
318 $group.finish(); // stop any current animations on the group
319 }
320 if ($group.css('display') === 'none' && !$group.hasClass('wpcf7cf-hidden')) {
321 if ($group.prop('tagName') === 'SPAN') {
322 $group.show().trigger('wpcf7cf_show_group'); // show instantly
323 } else {
324 $group.animate(wpcf7cf_show_animation, animation_intime).trigger('wpcf7cf_show_group'); // show with animation
325 }
326
327 if($group.attr('data-disable_on_hide') !== undefined) {
328 $group.find(':input').prop('disabled', false);
329 }
330
331 } else if ($group.css('display') !== 'none' && $group.hasClass('wpcf7cf-hidden')) {
332
333 if ($group.attr('data-clear_on_hide') !== undefined) {
334 var $inputs = jQuery(':input', $group).not(':button, :submit, :reset, :hidden');
335
336 $inputs.each(function(){
337 var $this = jQuery(this);
338 $this.val(this.defaultValue);
339 $this.prop('checked', this.defaultChecked);
340 });
341
342 jQuery('option', $group).each(function() {
343 this.selected = this.defaultSelected;
344 });
345
346 jQuery('select', $group).each(function() {
347 const $select = jQuery(this);
348 if ($select.val() === null) {
349 $select.val(jQuery("option:first",$select).val());
350 }
351 });
352
353 $inputs.trigger('change');
354 }
355
356 if ($group.prop('tagName') === 'SPAN') {
357 $group.hide().trigger('wpcf7cf_hide_group');
358 } else {
359 $group.animate(wpcf7cf_hide_animation, animation_outtime).trigger('wpcf7cf_hide_group'); // hide
360 }
361 }
362 });
363
364 form.updateHiddenFields();
365 form.updateSummaryFields();
366 };
367
368 Wpcf7cfForm.prototype.updateSummaryFields = function() {
369 const form = this;
370 var $summary = form.get('.wpcf7cf-summary');
371
372 if ($summary.length == 0 || !$summary.is(':visible')) return;
373
374 var fd = new FormData();
375
376 var formdata = form.$form.serializeArray();
377 jQuery.each(formdata,function(key, input){
378 fd.append(input.name, input.value);
379 });
380
381 // Make sure to add file fields to FormData
382 jQuery.each(form.$form.find('input[type="file"]'), function(index, el) {
383 if (! el.files.length) return true; // continue
384 const fieldName = el.name;
385 fd.append(fieldName, new Blob() , Array.from(el.files).map(file => file.name).join(', '));
386 });
387
388 // add file fields to form-data
389
390 jQuery.ajax({
391 url: wpcf7cf_global_settings.ajaxurl + '?action=wpcf7cf_get_summary',
392 type: 'POST',
393 data: fd,
394 processData: false,
395 contentType: false,
396 dataType: 'json',
397 success: function(json) {
398 $summary.html(json.summaryHtml);
399 }
400 });
401 };
402
403 Wpcf7cfForm.prototype.updateHiddenFields = function() {
404
405 var form = this;
406
407 var hidden_fields = [];
408 var hidden_groups = [];
409 var visible_groups = [];
410 var disabled_fields = [];
411
412 form.$groups.each(function () {
413 var $group = jQuery(this);
414 if ($group.hasClass('wpcf7cf-hidden')) {
415 hidden_groups.push($group.attr('data-id'));
416 $group.find('input,select,textarea').each(function () {
417 hidden_fields.push(jQuery(this).attr('name'));
418 });
419 if($group.attr('data-disable_on_hide') !== undefined) {
420 console.log('disabling');
421 $group.find(':input').prop('disabled', true);
422 }
423 } else {
424 visible_groups.push($group.attr('data-id'));
425 }
426 });
427
428 form.hidden_fields = hidden_fields;
429 form.hidden_groups = hidden_groups;
430 form.visible_groups = visible_groups;
431
432 form.$input_hidden_group_fields.val(JSON.stringify(hidden_fields));
433 form.$input_hidden_groups.val(JSON.stringify(hidden_groups));
434 form.$input_visible_groups.val(JSON.stringify(visible_groups));
435
436 return true;
437 };
438 Wpcf7cfForm.prototype.updateGroups = function() {
439 var form = this;
440 form.$groups = form.$form.find('[data-class="wpcf7cf_group"]');
441 form.$groups.height('auto');
442 form.conditions = window.wpcf7cf.get_nested_conditions(form.initial_conditions, form.$form);
443
444 };
445 Wpcf7cfForm.prototype.updateEventListeners = function() {
446
447 var form = this;
448
449 // monitor input changes, and call displayFields() if something has changed
450 form.get('input, select, textarea, button').not('.wpcf7cf_add, .wpcf7cf_remove').off(wpcf7cf_change_events).on(wpcf7cf_change_events,form, function(e) {
451 var form = e.data;
452 clearTimeout(wpcf7cf_timeout);
453 wpcf7cf_timeout = setTimeout(function() {
454 form.displayFields();
455 }, wpcf7cf_change_time_ms);
456 });
457
458 // PRO ONLY
459 form.get('.wpcf7cf-togglebutton').off('click.toggle_wpcf7cf').on('click.toggle_wpcf7cf',function() {
460 var $this = jQuery(this);
461 if ($this.text() === $this.attr('data-val-1')) {
462 $this.text($this.attr('data-val-2'));
463 $this.val($this.attr('data-val-2'));
464 } else {
465 $this.text($this.attr('data-val-1'));
466 $this.val($this.attr('data-val-1'));
467 }
468 });
469 // END PRO ONLY
470 };
471
472 // PRO ONLY
473 function Wpcf7cfRepeater($repeater, form) {
474 var $ = jQuery;
475
476 var repeater = this;
477
478 var wpcf7cf_settings = form.settings;
479
480 repeater.form = form;
481
482 $repeater.parentRepeaters = Array.from($repeater.parents('.wpcf7cf_repeater').map(function() {
483 return this.getAttribute('data-id');
484 } )).reverse();
485
486 $repeater.num_subs = 0;
487 $repeater.id = $repeater.attr('data-id');
488 $repeater.orig_id = $repeater.attr('data-orig_data_id');
489 $repeater.min = typeof( $repeater.attr('data-min')) !== 'undefined' ? parseInt($repeater.attr('data-min')) : 1;
490 $repeater.max = typeof( $repeater.attr('data-max')) !== 'undefined' ? parseInt($repeater.attr('data-max')) : 200;
491 $repeater.initial_subs = typeof( $repeater.attr('data-initial')) !== 'undefined' ? parseInt($repeater.attr('data-initial')) : $repeater.min;
492 if ($repeater.initial_subs > $repeater.max) $repeater.initial_subs = $repeater.max;
493 var $repeater_sub = $repeater.children('.wpcf7cf_repeater_sub').eq(0);
494 var $repeater_controls = $repeater.children('.wpcf7cf_repeater_controls').eq(0);
495
496 var $repeater_sub_clone = $repeater_sub.clone();
497
498 $repeater_sub_clone.find('.wpcf7cf_repeater_sub').addBack('.wpcf7cf_repeater_sub').each(function() {
499 var $this = jQuery(this);
500 var prev_suffix = $this.attr('data-repeater_sub_suffix');
501 var new_suffix = prev_suffix+'__{{repeater_sub_suffix}}';
502 $this.attr('data-repeater_sub_suffix', new_suffix);
503 });
504
505 $repeater_sub_clone.find('[name]').each(function() {
506 var $this = jQuery(this);
507 var prev_name = $this.attr('name');
508 var new_name = repeater.getNewName(prev_name);
509
510 var orig_name = $this.attr('data-orig_name') != null ? $this.attr('data-orig_name') : prev_name;
511
512 $this.attr('name', new_name);
513 $this.attr('data-orig_name', orig_name);
514 $this.closest('.wpcf7-form-control-wrap').addClass(new_name.replace('[]',''));
515 });
516
517 $repeater_sub_clone.find('.wpcf7cf_repeater,[data-class="wpcf7cf_group"]').each(function() {
518 var $this = jQuery(this);
519 var prev_data_id = $this.attr('data-id');
520 var orig_data_id = $this.attr('data-orig_data_id') != null ? $this.attr('data-orig_data_id') : prev_data_id;
521 var new_data_id = repeater.getNewName(prev_data_id);
522
523 if(prev_data_id.endsWith('_count')) {
524 new_data_id = prev_data_id.replace('_count','__{{repeater_sub_suffix}}_count');
525 }
526
527 $this.attr('data-id', new_data_id);
528 $this.attr('data-orig_data_id', orig_data_id);
529 });
530
531 $repeater_sub_clone.find('[id]').each(function() {
532 var $this = jQuery(this);
533 var prev_id = $this.attr('id');
534 var orig_id = $this.attr('data-orig_id') != null ? $this.attr('data-orig_id') : prev_id;
535 var new_id = repeater.getNewName(prev_id);
536
537 $this.attr('id', new_id);
538 $this.attr('data-orig_id', orig_id);
539 });
540
541 $repeater_sub_clone.find('[for]').each(function() {
542 var $this = jQuery(this);
543 var prev_for = $this.attr('for');
544 var orig_for = $this.attr('data-orig_for') != null ? $this.attr('data-orig_for') : prev_for;
545 var new_for = repeater.getNewName(prev_for);
546
547 $this.attr('for', new_for);
548 $this.attr('data-orig_for', orig_for);
549 });
550
551 var repeater_sub_html = $repeater_sub_clone[0].outerHTML;
552
553 var $repeater_count_field = $repeater.find('[name='+$repeater.id+'_count]').eq(0);
554 var $button_add = $repeater_controls.find('.wpcf7cf_add').eq(0);
555 var $button_remove = $repeater_controls.find('.wpcf7cf_remove').eq(0);
556
557 var params = {
558 $repeater: $repeater,
559 $repeater_count_field: $repeater_count_field,
560 repeater_sub_html: repeater_sub_html,
561 $repeater_controls: $repeater_controls,
562 $button_add: $button_add,
563 $button_remove: $button_remove,
564 wpcf7cf_settings: wpcf7cf_settings
565 };
566
567 this.params = params;
568
569 $button_add.on('click', null, repeater, function(e) {
570 var repeater = e.data;
571 repeater.updateSubs(params.$repeater.num_subs+1);
572 });
573
574 $button_remove.on('click', null, repeater,function(e) {
575 var repeater = e.data;
576 repeater.updateSubs(params.$repeater.num_subs-1);
577 });
578
579 jQuery('> .wpcf7cf_repeater_sub',params.$repeater).eq(0).remove(); // remove the first sub, it's just a template.
580
581 repeater.updateSubs($repeater.initial_subs);
582 repeater.updateButtons();
583
584 }
585
586 Wpcf7cfRepeater.prototype.getNewName = function(previousName) {
587 var prev_parts = previousName.split('[');
588 previousName = prev_parts[0];
589 var prev_suff = prev_parts.length > 1 ? '['+prev_parts.splice(1).join('[') : '';
590 var newName = previousName+'__{{repeater_sub_suffix}}'+prev_suff;
591
592 if(previousName.endsWith('_count')) {
593 newName = previousName.replace('_count','__{{repeater_sub_suffix}}_count');
594 }
595
596 return newName;
597 }
598
599 Wpcf7cfRepeater.prototype.updateButtons = function() {
600 const repeater = this;
601 const params = repeater.params;
602 const num_subs = params.$repeater.num_subs;
603
604 var showButtonRemove = false;
605 var showButtonAdd = false;
606
607 if (params.$repeater.num_subs < params.$repeater.max) {
608 showButtonAdd = true;
609 }
610 if (params.$repeater.num_subs > params.$repeater.min) {
611 showButtonRemove = true;
612 }
613
614 if (showButtonAdd) {
615 params.$button_add.show();
616 } else {
617 params.$button_add.hide();
618
619 }
620
621 if (showButtonRemove) {
622 params.$button_remove.show();
623 } else {
624 params.$button_remove.hide();
625 }
626
627 params.$repeater_count_field.val(num_subs);
628 }
629
630 Wpcf7cfRepeater.prototype.updateSubs = function(subs_to_show) {
631 var repeater = this;
632 var params = repeater.params;
633
634 // make sure subs_to_show is a valid number
635 subs_to_show = subs_to_show < params.$repeater.min ? params.$repeater.min : subs_to_show
636 subs_to_show = subs_to_show > params.$repeater.max ? params.$repeater.max : subs_to_show
637
638 var subs_to_add = subs_to_show - params.$repeater.num_subs;
639
640 if (subs_to_add < 0) {
641 repeater.removeSubs(-subs_to_add);
642 } else if (subs_to_add > 0) {
643 repeater.addSubs(subs_to_add);
644 }
645 };
646 /**
647 * add Subs to repeater
648 * @param {Number} subs_to_add
649 * @param {Number} index - zero-based. leave blank (or null) to append at the end
650 */
651 Wpcf7cfRepeater.prototype.addSubs = function(subs_to_add, index=null) {
652
653 var $ = jQuery;
654 var params = this.params;
655 var repeater = this;
656 var form = repeater.form;
657
658
659
660 var $repeater = params.$repeater;
661 var $repeater_controls = params.$repeater_controls;
662
663 if (subs_to_add + $repeater.num_subs > $repeater.max) {
664 subs_to_add = $repeater.max - $repeater.num_subs;
665 }
666
667 var html_str = '';
668
669 for(var i=1; i<=subs_to_add; i++) {
670 var sub_suffix = $repeater.num_subs+i;
671 html_str += params.repeater_sub_html.replace(/\{\{repeater_sub_suffix\}\}/g,sub_suffix)
672 .replace(new RegExp('\{\{'+$repeater.orig_id+'_index\}\}','g'),'<span class="wpcf7cf-index wpcf7cf__'+$repeater.orig_id+'">'+sub_suffix+'</span>');
673 }
674
675
676 var $html = jQuery(html_str);
677
678 jQuery('> .wpcf7cf_repeater_sub',$repeater).finish(); // finish any currently running animations immediately.
679
680 // Add the newly created fields to the form
681 if (index === null) {
682 $html.hide().insertBefore($repeater_controls).animate(wpcf7cf_show_animation, params.wpcf7cf_settings.animation_intime).trigger('wpcf7cf_repeater_added');
683 } else {
684 $html.hide().insertBefore(jQuery('> .wpcf7cf_repeater_sub', $repeater).eq(index)).animate(wpcf7cf_show_animation, params.wpcf7cf_settings.animation_intime).trigger('wpcf7cf_repeater_added');
685 }
686
687
688 jQuery('.wpcf7cf_repeater', $html).each(function(){
689 form.repeaters.push(new Wpcf7cfRepeater(jQuery(this),form));
690 });
691
692 form.$input_repeaters.val(JSON.stringify(form.repeaters.map((item)=>item.params.$repeater.id)));
693
694 $repeater.num_subs+= subs_to_add;
695
696 if (index !== null) {
697 repeater.updateSuffixes();
698 }
699
700 window.wpcf7cf.updateMultistepState(form.multistep);
701 form.updateGroups();
702 form.updateEventListeners();
703 form.displayFields();
704
705 repeater.updateButtons();
706
707 // Exclusive Checkbox
708 $html.on( 'click', '.wpcf7-exclusive-checkbox input:checkbox', function() {
709 var name = $( this ).attr( 'name' );
710 $html.find( 'input:checkbox[name="' + name + '"]' ).not( this ).prop( 'checked', false );
711 } );
712
713 //basic compatibility with material-design-for-contact-form-7
714 if (typeof window.cf7mdInit === "function") {
715 window.cf7mdInit();
716 }
717
718 return false;
719 };
720
721 /** TODO: implement this */
722 Wpcf7cfRepeater.prototype.updateSuffixes = function() {
723
724 // Loop trough all subs
725 // -- 1. update all fields, groups and repeaters names, id's, for's, ...
726 // -- 2. loop trough all repeaters
727 // -- update sub_html template for nested repeater
728 // -- call updateSuffixes() for nested repeater
729
730 var $repeater = this.params.$repeater;
731 var num_subs = this.params.$repeater.num_subs;
732 var form = this.form;
733 const orig_id = $repeater.attr('data-orig_data_id');
734 const repeater_id = $repeater.attr('data-id');
735 const repeater_suffix = repeater_id.replace(orig_id,'');
736
737 let simplifiedDomArray = Object.values(wpcf7cf.get_simplified_dom_model(form.$form[0]));
738
739 for (let i = 0; i < num_subs; i++) {
740
741 const $sub = jQuery('> .wpcf7cf_repeater_sub', $repeater).eq(i);
742
743 const newIndex = i+1;
744 const currentSuffix = $sub.attr('data-repeater_sub_suffix');
745 const newSuffix = repeater_suffix+'__'+newIndex;
746
747 $sub.attr('data-repeater_sub_suffix', newSuffix); // update sub attr
748 $sub.find('.wpcf7cf__'+orig_id).html(newIndex); // update {{r_index}} parts
749
750 simplifiedDomArray.forEach(function(el) {
751
752 if (el.suffix !== currentSuffix) return;
753
754 // TODO: may need an extra check to verify that the element is inside the current repeater
755 // (orig_id) . Otherwise problems may occur if there are repeaters on the same level.
756
757 const newName = el.name.replace(currentSuffix, newSuffix);
758
759 const pureElName = el.name.replace('[]','');
760 const pureNewName = newName.replace('[]','');
761
762 jQuery('[name="'+el.name+'"]', $sub).attr('name', newName);
763 jQuery('[id="'+el.name+'"]', $sub).attr('id', newName);
764 jQuery('label[for="'+el.name+'"]', $sub).attr('for', newName);
765 const $nested_repeater = jQuery('[data-id="'+el.name+'"]', $sub);
766 $nested_repeater.attr('data-id', newName);
767 jQuery('.wpcf7-form-control-wrap.'+pureElName,$sub).removeClass(pureElName).addClass(pureNewName);
768
769 if (el.type === 'repeater') {
770 const nested_repeater = form.repeaters.find( function(repeater) {
771 return repeater.params.$repeater.get(0) === $nested_repeater.get(0);
772 });
773
774 if (!nested_repeater) return;
775
776 nested_repeater.params.repeater_sub_html = wpcf7cf.updateRepeaterSubHTML(
777 nested_repeater.params.repeater_sub_html,
778 currentSuffix,
779 newSuffix,
780 nested_repeater.params.$repeater.parentRepeaters
781 );
782
783 nested_repeater.updateSuffixes();
784
785 }
786
787 });
788 }
789
790 };
791
792 /**
793 * Return the parent repeaters, order is not guaranteed.
794 */
795 Wpcf7cfRepeater.prototype.getParentRepeaters = function() {
796 const simplifiedDomArray = Object.values(wpcf7cf.get_simplified_dom_model(form.$form[0]));
797 form.repeaters.map(repeater => {
798
799 });
800 };
801
802 Wpcf7cfRepeater.prototype.removeSubs = function(subs_to_remove, index=null) {
803 var $ = jQuery;
804 var repeater = this;
805 var params = repeater.params;
806 var form = repeater.form;
807 var $repeater = params.$repeater;
808
809 if ($repeater.num_subs - subs_to_remove < $repeater.min) {
810 subs_to_remove = $repeater.num_subs - $repeater.min;
811 }
812
813 if (index===null) {
814 index = $repeater.num_subs-subs_to_remove;
815 }
816 $repeater.num_subs-= subs_to_remove;
817
818 jQuery('> .wpcf7cf_repeater_sub',$repeater).finish(); // finish any currently running animations immediately.
819
820 jQuery('> .wpcf7cf_repeater_sub',$repeater).slice(index,index+subs_to_remove).animate(wpcf7cf_hide_animation, {duration:params.wpcf7cf_settings.animation_intime, done:function() {
821 var $this = jQuery(this);
822 //remove the actual fields from the form
823 $this.remove();
824 params.$repeater.trigger('wpcf7cf_repeater_removed');
825 window.wpcf7cf.updateMultistepState(form.multistep);
826 form.updateGroups();
827 form.updateEventListeners();
828 form.displayFields();
829
830 repeater.updateButtons();
831
832 if (index !== null) {
833 repeater.updateSuffixes();
834 }
835 }});
836
837 return false;
838 };
839
840 function Wpcf7cfMultistep($multistep, form) {
841 var multistep = this;
842 multistep.$multistep = $multistep;
843 multistep.form = form;
844 multistep.$steps = $multistep.find('.wpcf7cf_step');
845 multistep.$btn_next = $multistep.find('.wpcf7cf_next');
846 multistep.$btn_prev = $multistep.find('.wpcf7cf_prev');
847 multistep.$dots = $multistep.find('.wpcf7cf_steps-dots');
848 multistep.currentStep = 0;
849 multistep.numSteps = multistep.$steps.length;
850
851
852 multistep.$dots.html('');
853 for (var i = 1; i <= multistep.numSteps; i++) {
854 multistep.$dots.append(`
855 <div class="dot" data-step="${i}">
856 <div class="step-index">${i}</div>
857 <div class="step-title">${multistep.$steps.eq(i-1).attr('data-title')}</div>
858 </div>
859 `);
860 }
861
862 multistep.$btn_next.on('click.wpcf7cf_step', async function() {
863
864 multistep.$btn_next.addClass('disabled').attr('disabled', true);
865
866 var result = await multistep.validateStep(multistep.currentStep);
867 if (result === 'success') {
868 multistep.moveToStep(multistep.currentStep+1);
869 }
870
871 });
872
873 // If form is submitted (by pressing Enter for example), and if we are not on the last step,
874 // then trigger click event on the $btn_next button instead.
875 multistep.form.$form.on('submit.wpcf7cf_step', function(e) {
876
877 if (multistep.currentStep !== multistep.numSteps) {
878 multistep.$btn_next.trigger('click.wpcf7cf_step');
879
880 e.stopImmediatePropagation();
881 return false;
882 }
883 });
884
885 multistep.$btn_prev.on( 'click', function() {
886 multistep.moveToStep(multistep.currentStep-1);
887 });
888
889 multistep.moveToStep(1);
890 }
891
892 jQuery(document).ajaxComplete(function(e, xhr, settings){
893 if (
894 xhr.hasOwnProperty('responseJSON') &&
895 xhr.responseJSON != null &&
896 xhr.responseJSON.hasOwnProperty('status') &&
897 xhr.responseJSON.hasOwnProperty('into') &&
898 xhr.responseJSON.status === "mail_success"
899 ) {
900 jQuery( xhr.responseJSON.into ).trigger('reset.wpcf7cf');
901 }
902 });
903
904 Wpcf7cfMultistep.prototype.validateStep = function(step_index) {
905
906 var multistep = this;
907 var $multistep = multistep.$multistep;
908 var $form = multistep.form.$form;
909 var form = multistep.form;
910
911 $form.find('.wpcf7-response-output').addClass('wpcf7-display-none');
912
913 return new Promise(resolve => {
914
915 var fd = new FormData();
916
917 // Make sure to add file fields to FormData
918 jQuery.each($form.find('[data-id="step-'+step_index+'"] input[type="file"]'), function(index, el) {
919 if (! el.files.length) return true; // = continue
920 const file = el.files[0];
921 const fieldName = el.name;
922 fd.append(fieldName, file);
923 });
924
925 var formdata = $form.serializeArray();
926 jQuery.each(formdata,function(key, input){
927 fd.append(input.name, input.value);
928 });
929
930 jQuery.ajax({
931 url: wpcf7cf_global_settings.ajaxurl + '?action=wpcf7cf_validate_step',
932 type: 'POST',
933 data: fd,
934 processData: false,
935 contentType: false,
936 dataType: 'json',
937 }).done(function(json) {
938
939 $multistep.find('.wpcf7-form-control-wrap .wpcf7-not-valid-tip').remove();
940 $multistep.find('.wpcf7-not-valid').removeClass('wpcf7-not-valid');
941 $multistep.find('.wpcf7-response-output').remove();
942 $multistep.find('.wpcf7-response-output.wpcf7-validation-errors').removeClass('wpcf7-validation-errors');
943
944 multistep.$btn_next.removeClass('disabled').attr('disabled', false);
945
946 if (!json.success) {
947 var checkError = 0;
948
949 jQuery.each(json.invalid_fields, function(index, el) {
950 if ($multistep.find('input[name="'+index+'"]').length ||
951 $multistep.find('input[name="'+index+'[]"]').length ||
952 $multistep.find('select[name="'+index+'"]').length ||
953 $multistep.find('select[name="'+index+'[]"]').length ||
954 $multistep.find('textarea[name="'+index+'"]').length ||
955 $multistep.find('textarea[name="'+index+'[]"]').length
956 ) {
957 checkError = checkError + 1;
958
959 var controlWrap = form.get('.wpcf7-form-control-wrap.' + index);
960 controlWrap.find('.wpcf7-form-control').addClass('wpcf7-not-valid');
961 controlWrap.find('span.wpcf7-not-valid-tip').remove();
962 controlWrap.append('<span role="alert" class="wpcf7-not-valid-tip">' + el.reason + '</span>');
963
964 }
965 });
966
967 resolve('failed');
968
969 $multistep.parent().find('.wpcf7-response-output').removeClass('wpcf7-display-none').html(json.message);
970
971 wpcf7.setStatus( $form, 'invalid' );
972 multistep.$steps.trigger('wpcf7cf_step_invalid');
973
974 // wpcf7.triggerEvent( data.into, 'invalid', detail );
975
976 } else if (json.success) {
977
978 wpcf7.setStatus( $form, 'init' );
979
980 resolve('success');
981 return false;
982 }
983
984 }).fail(function() {
985 resolve('error');
986 }).always(function() {
987 // do nothing
988 });
989 });
990
991 };
992 Wpcf7cfMultistep.prototype.moveToStep = function(step_index) {
993 var multistep = this;
994 var previousStep = multistep.currentStep;
995
996 multistep.currentStep = step_index > multistep.numSteps ? multistep.numSteps
997 : step_index < 1 ? 1
998 : step_index;
999
1000 // ANIMATION DISABLED FOR NOW cause it's ugly
1001 // multistep.$steps.animate(wpcf7cf_hide_step_animation, multistep.form.settings.animation_outtime);
1002 // multistep.$steps.eq(multistep.currentStep-1).animate(wpcf7cf_show_step_animation, multistep.form.settings.animation_intime);
1003
1004 multistep.$multistep.attr('data-current_step', multistep.currentStep);
1005 multistep.$steps.hide();
1006 multistep.$steps
1007 .eq(multistep.currentStep-1)
1008 .show()
1009 .trigger('wpcf7cf_change_step', [previousStep, multistep.currentStep]);
1010
1011 const formEl = multistep.form.$form[0];
1012 const topOffset = formEl.getBoundingClientRect().top;
1013 if (topOffset < 0 && previousStep > 0) {
1014 formEl.scrollIntoView({behavior: "smooth"});
1015 }
1016
1017 multistep.form.updateSummaryFields();
1018
1019 window.wpcf7cf.updateMultistepState(multistep);
1020 };
1021
1022 Wpcf7cfMultistep.prototype.getFieldsInStep = function(step_index) {
1023 wpcf7cf_reload_dom(this.form.$form);
1024 var inStep = false;
1025 return Object.values(wpcf7cf_dom).filter(function(item, i) {
1026 if(item.type == 'step') {
1027 inStep = item.val == step_index+'';
1028 }
1029 return inStep && item.type == 'input';
1030 }).map(function(item) {
1031 return item.name;
1032 });
1033 };
1034
1035 // END PRO ONLY
1036
1037 /**
1038 * @global
1039 * @namespace wpcf7cf
1040 */
1041 window.wpcf7cf = {
1042
1043 hideGroup : function($group, animate) {
1044
1045 },
1046
1047 showGroup : function($group, animate) {
1048
1049 },
1050
1051 updateRepeaterSubHTML : function(html, oldSuffix, newSuffix, parentRepeaters) {
1052 const oldIndexes = oldSuffix.split('__');
1053 oldIndexes.shift(); // remove first empty element
1054 const newIndexes = newSuffix.split('__');
1055 newIndexes.shift(); // remove first empty element
1056
1057 let returnHtml = html;
1058
1059 if (
1060 oldIndexes && newIndexes &&
1061 oldIndexes.length === parentRepeaters.length &&
1062 newIndexes.length === parentRepeaters.length
1063 ) {
1064
1065 const parentRepeatersInfo = parentRepeaters.map((repeaterId, i) => {
1066 return {[repeaterId.split('__')[0]]: [oldIndexes[i], newIndexes[i]]};
1067 });
1068
1069 const length = parentRepeatersInfo.length;
1070
1071 let replacements = oldIndexes.map( (oldIndex, i) => {
1072 return [
1073 '__'+oldIndexes.slice(0,length-i).join('__'),
1074 '__'+newIndexes.slice(0,length-i).join('__'),
1075 ];
1076 });
1077
1078
1079 for (let i=0; i<length ; i++) {
1080 const id = Object.keys(parentRepeatersInfo[i])[0];
1081 const find = parentRepeatersInfo[i][id][0];
1082 const repl = parentRepeatersInfo[i][id][1];
1083 replacements.push([
1084 `<span class="wpcf7cf-index wpcf7cf__${id}">${find}<\\/span>`,
1085 `<span class="wpcf7cf-index wpcf7cf__${id}">${repl}</span>`
1086 ]);
1087 }
1088
1089 replacements.forEach( ([oldSuffix, newSuffix]) => {
1090 returnHtml = returnHtml.replace(new RegExp(oldSuffix,'g'), newSuffix);
1091 });
1092
1093 }
1094
1095 return returnHtml ;
1096 },
1097
1098 // keep this for backwards compatibility
1099 initForm : function($forms) {
1100 $forms.each(function(){
1101 const $form = jQuery(this);
1102 // only add form is its class is "wpcf7-form" and if the form was not previously added
1103 if (
1104 $form.hasClass('wpcf7-form') &&
1105 !wpcf7cf_forms.some((form)=>{ return form.$form.get(0) === $form.get(0); })
1106 ) {
1107 wpcf7cf_forms.push(new Wpcf7cfForm($form));
1108 }
1109 });
1110 },
1111
1112 getWpcf7cfForm : function ($form) {
1113 const matched_forms = wpcf7cf_forms.filter((form)=>{
1114 const f1 = form.$form.get(0);
1115 const f2 = $form.get(0);
1116 return form.$form.get(0) === $form.get(0);
1117 });
1118 if (matched_forms.length) {
1119 return matched_forms[0];
1120 }
1121 return false;
1122 },
1123
1124 get_nested_conditions : function(conditions, $current_form) {
1125 //loop trough conditions. Then loop trough the dom, and each repeater we pass we should update all sub_values we encounter with __index
1126 wpcf7cf_reload_dom($current_form);
1127 var groups = Object.values(wpcf7cf_dom).filter(function(item, i) {
1128 return item.type==='group';
1129 });
1130
1131 var sub_conditions = [];
1132
1133 for(var i = 0; i < groups.length; i++) {
1134 var g = groups[i];
1135 var relevant_conditions = conditions.filter(function(condition, i) {
1136 return condition.then_field === g.original_name;
1137 });
1138
1139 var relevant_conditions = relevant_conditions.map(function(item,i) {
1140 return {
1141 then_field : g.name,
1142 and_rules : item.and_rules.map(function(and_rule, i) {
1143 return {
1144 if_field : and_rule.if_field+g.suffix,
1145 if_value : and_rule.if_value,
1146 operator : and_rule.operator
1147 };
1148 })
1149 }
1150 });
1151
1152 sub_conditions = sub_conditions.concat(relevant_conditions);
1153 }
1154 return sub_conditions;
1155 },
1156
1157 get_simplified_dom_model : function(currentNode, simplified_dom = {}, parentGroups = [], parentRepeaters = []) {
1158
1159 const type = currentNode.classList && currentNode.classList.contains('wpcf7cf_repeater') ? 'repeater' :
1160 currentNode.dataset.class == 'wpcf7cf_group' ? 'group' :
1161 currentNode.className == 'wpcf7cf_step' ? 'step' :
1162 currentNode.hasAttribute('name') && !currentNode.disabled ? 'input' : false;
1163
1164 let newParentRepeaters = [...parentRepeaters];
1165 let newParentGroups = [...parentGroups];
1166
1167 if (type) {
1168
1169
1170 const name = type === 'input' ? currentNode.getAttribute('name') : currentNode.dataset.id;
1171
1172 if (type === 'repeater') {
1173 newParentRepeaters.push(name);
1174 }
1175 if (type === 'group') {
1176 newParentGroups.push(name);
1177 }
1178
1179 // skip _wpcf7 hidden fields
1180 if (name.substring(0,6) === '_wpcf7') return {};
1181
1182 const original_name = type === 'repeater' || type === 'group' ? currentNode.dataset.orig_data_id
1183 : type === 'input' ? (currentNode.getAttribute('data-orig_name') || name)
1184 : name;
1185
1186 const nameWithoutBrackets = name.replace('[]','');
1187 const originalNameWithoutBrackets = original_name.replace('[]','');
1188
1189 const val = type === 'step' ? [currentNode.dataset.id.substring(5)] : [];
1190
1191 const parentGroup = 'parent-group';
1192
1193 const suffix = nameWithoutBrackets.replace(originalNameWithoutBrackets, '');
1194
1195 if (!simplified_dom[name]) {
1196 // init entry
1197 simplified_dom[name] = {name, type, original_name, suffix, val, parentGroups, parentRepeaters}
1198 }
1199
1200 if (type === 'input') {
1201
1202 // skip unchecked checkboxes and radiobuttons
1203 if ( (currentNode.type === 'checkbox' || currentNode.type === 'radio') && !currentNode.checked ) return {};
1204
1205 // if multiselect, make sure to add all the values
1206 if ( currentNode.multiple && currentNode.options ) {
1207 simplified_dom[name].val = Object.values(currentNode.options).filter(o => o.selected).map(o => o.value)
1208 } else {
1209 simplified_dom[name].val.push(currentNode.value);
1210 }
1211 }
1212 }
1213
1214 Array.from(currentNode.children).forEach(childNode => {
1215 const dom = wpcf7cf.get_simplified_dom_model(childNode, simplified_dom, newParentGroups, newParentRepeaters);
1216 simplified_dom = {...dom, ...simplified_dom} ;
1217 });
1218
1219 return simplified_dom;
1220 },
1221
1222 updateMultistepState: function (multistep) {
1223 if (multistep == null) return;
1224
1225 // update hidden input field
1226
1227 var stepsData = {
1228 currentStep : multistep.currentStep,
1229 numSteps : multistep.numSteps,
1230 fieldsInCurrentStep : multistep.getFieldsInStep(multistep.currentStep)
1231 };
1232 multistep.form.$input_steps.val(JSON.stringify(stepsData));
1233
1234 // update Buttons
1235 multistep.$btn_prev.removeClass('disabled').attr('disabled', false);
1236 multistep.$btn_next.removeClass('disabled').attr('disabled', false);
1237 if (multistep.currentStep == multistep.numSteps) {
1238 multistep.$btn_next.addClass('disabled').attr('disabled', true);
1239 }
1240 if (multistep.currentStep == 1) {
1241 multistep.$btn_prev.addClass('disabled').attr('disabled', true);
1242 }
1243
1244 // replace next button with submit button on last step.
1245 // TODO: make this depend on a setting
1246 var $submit_button = multistep.form.$form.find('input[type="submit"]').eq(0);
1247 var $ajax_loader = multistep.form.$form.find('.ajax-loader').eq(0);
1248 if (multistep.currentStep == multistep.numSteps) {
1249 multistep.$btn_next.hide();
1250 $ajax_loader.detach().appendTo(multistep.$btn_next.parent());
1251 $submit_button.detach().appendTo(multistep.$btn_next.parent());
1252 $submit_button.show();
1253 } else {
1254 $submit_button.hide();
1255 multistep.$btn_next.show();
1256 }
1257
1258 // update dots
1259 var $dots = multistep.$dots.find('.dot');
1260 $dots.removeClass('active').removeClass('completed');
1261 for(var step = 1; step <= multistep.numSteps; step++) {
1262 if (step < multistep.currentStep) {
1263 $dots.eq(step-1).addClass('completed');
1264 } else if (step == multistep.currentStep) {
1265 $dots.eq(step-1).addClass('active');
1266 }
1267 }
1268
1269 },
1270
1271 should_group_be_shown : function(condition) {
1272
1273 var show_group = true;
1274
1275 for (var and_rule_i = 0; and_rule_i < condition.and_rules.length; and_rule_i++) {
1276
1277 var condition_ok = false;
1278
1279 var condition_and_rule = condition.and_rules[and_rule_i];
1280
1281 var inputField = wpcf7cf_getFieldByName(condition_and_rule.if_field);
1282
1283 if (!inputField) continue; // field not found
1284
1285 var if_val = condition_and_rule.if_value;
1286 var operator = condition_and_rule.operator;
1287
1288 //backwards compat
1289 operator = operator === '' ? 'less than or equals' : operator;
1290 operator = operator === '' ? 'greater than or equals' : operator;
1291 operator = operator === '>' ? 'greater than' : operator;
1292 operator = operator === '<' ? 'less than' : operator;
1293
1294 const $field = operator === 'function' && jQuery(`[name="${inputField.name}"]`).eq(0);
1295
1296 condition_ok = this.isConditionTrue(inputField.val,operator,if_val, $field);
1297
1298 show_group = show_group && condition_ok;
1299 }
1300
1301 return show_group;
1302
1303 },
1304
1305 isConditionTrue(values, operator, testValue='', $field=jQuery()) {
1306
1307 if (!Array.isArray(values)) {
1308 values = [values];
1309 }
1310
1311 let condition_ok = false; // start by assuming that the condition is not met
1312
1313 // Considered EMPTY: [] [''] [null] ['',null] [,,'']
1314 // Considered NOT EMPTY: [0] ['ab','c'] ['',0,null]
1315 const valuesAreEmpty = values.length === 0 || values.every((v) => !v&&v!==0); // 0 is not considered empty
1316
1317 // special cases: [] equals '' => TRUE; [] not equals '' => FALSE
1318 if (operator === 'equals' && testValue === '' && valuesAreEmpty) {
1319 return true;
1320 }
1321 if (operator === 'not equals' && testValue === '' && valuesAreEmpty) {
1322 return false;
1323 }
1324
1325 if (valuesAreEmpty) {
1326 if (operator === 'is empty') {
1327 condition_ok = true;
1328 }
1329 } else {
1330 if (operator === 'not empty') {
1331 condition_ok = true;
1332 }
1333 }
1334
1335 const testValueNumber = isFinite(parseFloat(testValue)) ? parseFloat(testValue) : NaN;
1336
1337
1338 if (operator === 'not equals' || operator === 'not equals (regex)') {
1339 // start by assuming that the condition is met
1340 condition_ok = true;
1341 }
1342
1343 if (
1344 operator === 'function'
1345 && typeof window[testValue] == 'function'
1346 && window[testValue]($field) // here we call the actual user defined function
1347 ) {
1348 condition_ok = true;
1349 }
1350
1351 let regex_patt = /.*/i; // fallback regex pattern
1352 let isValidRegex = true;
1353 if (operator === 'equals (regex)' || operator === 'not equals (regex)') {
1354 try {
1355 regex_patt = new RegExp(testValue, 'i');
1356 } catch(e) {
1357 isValidRegex = false;
1358 }
1359 }
1360
1361
1362 for(let i = 0; i < values.length; i++) {
1363
1364 const value = values[i];
1365
1366 const valueNumber = isFinite(parseFloat(value)) ? parseFloat(value) : NaN;
1367 const valsAreNumbers = !isNaN(valueNumber) && !isNaN(testValueNumber);
1368
1369 if (
1370
1371 operator === 'equals' && value === testValue ||
1372 operator === 'equals (regex)' && regex_patt.test(value) ||
1373 operator === 'greater than' && valsAreNumbers && valueNumber > testValueNumber ||
1374 operator === 'less than' && valsAreNumbers && valueNumber < testValueNumber ||
1375 operator === 'greater than or equals' && valsAreNumbers && valueNumber >= testValueNumber ||
1376 operator === 'less than or equals' && valsAreNumbers && valueNumber <= testValueNumber
1377
1378 ) {
1379
1380 condition_ok = true;
1381 break;
1382
1383 } else if (
1384
1385 operator === 'not equals' && value === testValue ||
1386 operator === 'not equals (regex)' && regex_patt.test(value)
1387
1388 ) {
1389
1390 condition_ok = false;
1391 break;
1392
1393 }
1394 }
1395
1396 return condition_ok;
1397
1398 },
1399
1400 getFormObj($form) {
1401 if (typeof $form === 'string') {
1402 $form = jQuery($form).eq(0);
1403 }
1404 return wpcf7cf.getWpcf7cfForm($form);
1405 },
1406
1407 getRepeaterObj($form, repeaterDataId) {
1408 const form = wpcf7cf.getFormObj($form);
1409 const repeater = form.repeaters.find( repeater => repeater.params.$repeater.attr('data-id') === repeaterDataId );
1410
1411 return repeater;
1412
1413 },
1414
1415 getMultiStepObj($form){
1416 const form = wpcf7cf.getFormObj($form);
1417 return form.multistep;
1418 },
1419
1420 /**
1421 * Append a new sub-entry to the repeater with the name `repeaterDataId` inside the form `$form`
1422 * @memberof wpcf7cf
1423 * @function wpcf7cf.repeaterAddSub
1424 * @link
1425 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
1426 * @param {String} repeaterDataId - *data-id* attribute of the repeater. Normally this is simply the name of the repeater. However, in case of a nested repeater you need to append the name with the correct suffix. For example `my-nested-repeater__1__3`. Hint (check the `data-id` attribute in the HTML code to find the correct suffix)
1427 */
1428 repeaterAddSub($form,repeaterDataId) {
1429 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
1430 repeater.updateSubs(repeater.params.$repeater.num_subs+1);
1431 },
1432
1433 /**
1434 * Insert a new sub-entry at the given `index` of the repeater with the name `repeaterDataId` inside the form `$form`
1435 * @memberof wpcf7cf
1436 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
1437 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
1438 * @param {Number} index - position where to insert the new sub-entry within the repeater
1439 */
1440 repeaterAddSubAtIndex($form,repeaterDataId,index) {
1441 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
1442 repeater.addSubs(1, index);
1443 },
1444
1445 /**
1446 * Remove the sub-entry at the given `index` of the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`
1447 * @memberof wpcf7cf
1448 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
1449 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
1450 * @param {Number} index - position where to insert the new sub-entry within the repeater
1451 */
1452 repeaterRemoveSubAtIndex($form,repeaterDataId,index) {
1453 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
1454 repeater.removeSubs(1, index);
1455 },
1456
1457 /**
1458 * Remove the last sub-entry from the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`
1459 * @memberof wpcf7cf
1460 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
1461 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
1462 * @param {Number} index - position where to insert the new sub-entry within the repeater
1463 */
1464 repeaterRemoveSub($form,repeaterDataId) {
1465 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
1466 repeater.updateSubs(repeater.params.$repeater.num_subs-1);
1467 },
1468
1469 /**
1470 * Set the number of subs for the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`.
1471 * Subs are either appended to or removed from the end of the repeater.
1472 * @memberof wpcf7cf
1473 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
1474 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
1475 * @param {Number} numberOfSubs - position where to insert the new sub-entry within the repeater
1476 */
1477 repeaterSetNumberOfSubs($form, repeaterDataId, numberOfSubs) {
1478 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
1479 repeater.updateSubs(numberOfSubs);
1480 },
1481
1482 /**
1483 * Move to step number `step`, ignoring any validation.
1484 * @memberof wpcf7cf
1485 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
1486 * @param {*} step
1487 */
1488 multistepMoveToStep($form, step) {
1489 const multistep = wpcf7cf.getMultiStepObj($form);
1490 multistep.moveToStep(step);
1491 },
1492
1493 /**
1494 * Validate the current step, and move to step number `step` if validation passes.
1495 * @memberof wpcf7cf
1496 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
1497 * @param {Number} step
1498 */
1499 async multistepMoveToStepWithValidation($form, step) {
1500 const multistep = wpcf7cf.getMultiStepObj($form);
1501
1502 var result = await multistep.validateStep(multistep.currentStep);
1503 if (result === 'success') {
1504 multistep.moveToStep(step);
1505 }
1506 },
1507
1508
1509 };
1510
1511 jQuery('.wpcf7-form').each(function(){
1512 wpcf7cf_forms.push(new Wpcf7cfForm(jQuery(this)));
1513 });
1514
1515 // Call displayFields again on all forms
1516 // Necessary in case some theme or plugin changed a form value by the time the entire page is fully loaded.
1517 jQuery('document').on('ready',function() {
1518 wpcf7cf_forms.forEach(function(f){
1519 f.displayFields();
1520 });
1521 });
1522
1523 // fix for exclusive checkboxes in IE (this will call the change-event again after all other checkboxes are unchecked, triggering the display_fields() function)
1524 var old_wpcf7ExclusiveCheckbox = jQuery.fn.wpcf7ExclusiveCheckbox;
1525 jQuery.fn.wpcf7ExclusiveCheckbox = function() {
1526 return this.find('input:checkbox').on('click', function() {
1527 var name = jQuery(this).attr('name');
1528 jQuery(this).closest('form').find('input:checkbox[name="' + name + '"]').not(this).prop('checked', false).eq(0).change();
1529 });
1530 };