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