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