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