PluginProbe ʕ •ᴥ•ʔ
Conditional Fields for Contact Form 7 / 2.7.10
Conditional Fields for Contact Form 7 v2.7.10
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 / jsdoc-out / scripts.js.html
cf7-conditional-fields / jsdoc-out Last commit date
fonts 5 years ago scripts 5 years ago styles 5 years ago global.html 1 day ago index.html 1 day ago module-wpcf7cf.html 5 years ago scripts.js.html 1 day ago scripts_es6.js.html 4 years ago wpcf7cf.html 1 day ago wpcf7cfApi.html 5 years ago
scripts.js.html
1034 lines
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>JSDoc: Source: scripts.js</title>
6
7 <script src="scripts/prettify/prettify.js"> </script>
8 <script src="scripts/prettify/lang-css.js"> </script>
9 <!--[if lt IE 9]>
10 <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
11 <![endif]-->
12 <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
13 <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
14 </head>
15
16 <body>
17
18 <div id="main">
19
20 <h1 class="page-title">Source: scripts.js</h1>
21
22
23
24
25
26
27 <section>
28 <article>
29 <pre class="prettyprint source linenums"><code>"use strict";
30
31 let cf7signature_resized = 0; // for compatibility with contact-form-7-signature-addon
32
33 let wpcf7cf_timeout;
34 let wpcf7cf_change_time_ms = 100; // the timeout after a change in the form is detected
35
36 // needed for multistep validation
37 if (window.wpcf7 &amp;&amp; !wpcf7.setStatus) {
38 wpcf7.setStatus = ( form, status ) => {
39 form = form.length ? form[0] : form; // if form is a jQuery object, only grab te html-element
40 const defaultStatuses = new Map( [
41 // 0: Status in API response, 1: Status in HTML class
42 [ 'init', 'init' ],
43 [ 'validation_failed', 'invalid' ],
44 [ 'acceptance_missing', 'unaccepted' ],
45 [ 'spam', 'spam' ],
46 [ 'aborted', 'aborted' ],
47 [ 'mail_sent', 'sent' ],
48 [ 'mail_failed', 'failed' ],
49 [ 'submitting', 'submitting' ],
50 [ 'resetting', 'resetting' ],
51 ] );
52
53 if ( defaultStatuses.has( status ) ) {
54 status = defaultStatuses.get( status );
55 }
56
57 if ( ! Array.from( defaultStatuses.values() ).includes( status ) ) {
58 status = status.replace( /[^0-9a-z]+/i, ' ' ).trim();
59 status = status.replace( /\s+/, '-' );
60 status = `custom-${ status }`;
61 }
62
63 const prevStatus = form.getAttribute( 'data-status' );
64
65 form.wpcf7.status = status;
66 form.setAttribute( 'data-status', status );
67 form.classList.add( status );
68
69 if ( prevStatus &amp;&amp; prevStatus !== status ) {
70 form.classList.remove( prevStatus );
71 }
72
73 return status;
74 };
75 }
76
77 if (window.wpcf7cf_running_tests) {
78 document.querySelectorAll('input[name="_wpcf7cf_options"]').forEach(input => {
79 const opt = JSON.parse(input.value);
80 opt.settings.animation_intime = 0;
81 opt.settings.animation_outtime = 0;
82 input.value = JSON.stringify(opt);
83 });
84 wpcf7cf_change_time_ms = 0;
85 }
86
87 const wpcf7cf_show_animation = { "height": "show", "marginTop": "show", "marginBottom": "show", "paddingTop": "show", "paddingBottom": "show" };
88 const wpcf7cf_hide_animation = { "height": "hide", "marginTop": "hide", "marginBottom": "hide", "paddingTop": "hide", "paddingBottom": "hide" };
89
90 const wpcf7cf_show_step_animation = { "opacity": "show" };
91 const wpcf7cf_hide_step_animation = { "opacity": "hide" };
92
93 const wpcf7cf_change_events = 'input.wpcf7cf paste.wpcf7cf change.wpcf7cf click.wpcf7cf propertychange.wpcf7cf changedisabledprop.wpcf7cf';
94
95 const wpcf7cf_forms = [];
96
97 const Wpcf7cfForm = function(formElement) {
98
99 const $form = jQuery(formElement);
100
101 const options_element = $form.find('input[name="_wpcf7cf_options"]').eq(0);
102 if (!options_element.length || !options_element.val()) {
103 // doesn't look like a CF7 form created with conditional fields plugin enabled.
104 return false;
105 }
106
107 const form = this;
108
109 // always wait until groups are updated before submitting the form
110 formElement.addEventListener('submit', function(e) {
111 if (window.wpcf7cf_updatingGroups) {
112 e.preventDefault();
113 e.stopImmediatePropagation();
114
115 // Wait until updatingGroups is false, then submit again
116 const retry = () => {
117 if (!window.wpcf7cf_updatingGroups) {
118 $form.off('.wpcf7cf-autosubmit'); // prevent duplicates
119 formElement.requestSubmit(); // safe submit
120 } else {
121 requestAnimationFrame(retry);
122 }
123 };
124
125 // Attach listener to prevent loop if user resubmits manually
126 $form.on('submit.wpcf7cf-autosubmit', (e) => e.preventDefault());
127
128 retry(); // start retry loop
129 return false;
130 }
131 }, true); // use capture to run before WP's own handler
132
133 // Disable submit buttons only during the actual submit, then restore prior state — don't clobber CF7's acceptance gating or any custom disabling (#136)
134 const submitButtons = formElement.querySelectorAll('button[type=submit], input[type=submit]');
135 const prevDisabled = new WeakMap();
136 let wasSubmitting = formElement.classList.contains('submitting');
137 const observer = new MutationObserver(() => {
138 const isSubmitting = formElement.classList.contains('submitting');
139 if (isSubmitting === wasSubmitting) return; // only act on the submitting transition
140 wasSubmitting = isSubmitting;
141
142 submitButtons.forEach(button => {
143 if (isSubmitting) {
144 prevDisabled.set(button, button.disabled);
145 button.disabled = true;
146 button.classList.add('is-disabled');
147 } else {
148 button.disabled = prevDisabled.get(button) || false;
149 button.classList.remove('is-disabled');
150 }
151 });
152 });
153 observer.observe(formElement, { attributes: true, attributeFilter: ['class'] });
154
155 const form_options = JSON.parse(options_element.val());
156
157 form.$form = $form;
158 form.formElement = formElement;
159 form.$input_hidden_group_fields = $form.find('[name="_wpcf7cf_hidden_group_fields"]');
160 form.$input_hidden_groups = $form.find('[name="_wpcf7cf_hidden_groups"]');
161 form.$input_visible_groups = $form.find('[name="_wpcf7cf_visible_groups"]');
162 form.$input_repeaters = $form.find('[name="_wpcf7cf_repeaters"]');
163 form.$input_steps = $form.find('[name="_wpcf7cf_steps"]');
164
165 form.unit_tag = $form.closest('.wpcf7').attr('id');
166 form.conditions = form_options['conditions'];
167
168 form.simpleDom = null;
169
170 form.reloadSimpleDom = function() {
171 form.simpleDom = wpcf7cf.get_simplified_dom_model(form.formElement);
172 }
173
174 // quicker than reloading the simpleDom completely with reloadSimpleDom
175 form.updateSimpleDom = function() {
176 if (!form.simpleDom) {
177 form.reloadSimpleDom();
178 }
179 const inputs = Object.values(form.simpleDom).filter(item => item.type === 'input');
180 const formdata = new FormData(form.formElement);
181
182 let formdataEntries = [... formdata.entries()].map(entry => [ entry[0], entry[1].name ?? entry[1] ]);
183 const buttonEntries = Array.from(form.formElement.querySelectorAll('button'), b => [b.name, b.value]);
184 formdataEntries = formdataEntries.concat(buttonEntries);
185
186 inputs.forEach(simpleDomItem => {
187 const newValue = form.getNewDomValueIfChanged(simpleDomItem, formdataEntries);
188 if (newValue !== null) {
189 form.simpleDom[simpleDomItem.name].val = newValue;
190 }
191 });
192
193 }
194
195 form.isDomMatch = function(simpleDomItem, formDataEntries) {
196 const simpleDomItemName = simpleDomItem.name;
197 const simpleDomItemValues = simpleDomItem.val;
198 const currentValues = formDataEntries.filter(entry => entry[0] === simpleDomItemName).map(entry => entry[1]);
199 return currentValues.join('|') === simpleDomItemValues.join('|');
200 }
201
202 /**
203 *
204 * @param {*} simpleDomItem
205 * @param {*} formDataEntries
206 * @returns the new value, or NULL if no change
207 */
208 form.getNewDomValueIfChanged = function(simpleDomItem, formDataEntries) {
209 const simpleDomItemName = simpleDomItem.name;
210 const simpleDomItemValues = simpleDomItem.val;
211 const currentValues = formDataEntries.filter(entry => entry[0] === simpleDomItemName).map(entry => entry[1]);
212 return currentValues.join('|') === simpleDomItemValues.join('|') ? null : currentValues;
213 }
214
215 // Wrapper around jQuery(selector, form.$form)
216 form.get = function (selector) {
217 // TODO: implement some caching here.
218 return jQuery(selector, form.$form);
219 }
220
221 form.getFieldByName = function(name) {
222 return form.simpleDom[name] || form.simpleDom[name+'[]'];
223 }
224
225 // compatibility with conditional forms created with older versions of the plugin ( &lt; 1.4 )
226 for (let i=0; i &lt; form.conditions.length; i++) {
227 const condition = form.conditions[i];
228 if (!('and_rules' in condition)) {
229 condition.and_rules = [{'if_field':condition.if_field,'if_value':condition.if_value,'operator':condition.operator}];
230 }
231 }
232
233 form.initial_conditions = form.conditions;
234 form.settings = form_options['settings'];
235
236 form.$groups = jQuery(); // empty jQuery set
237 form.repeaters = [];
238 form.multistep = null;
239 form.fields = [];
240
241 form.settings.animation_intime = parseInt(form.settings.animation_intime);
242 form.settings.animation_outtime = parseInt(form.settings.animation_outtime);
243
244 if (form.settings.animation === 'no') {
245 form.settings.animation_intime = 0;
246 form.settings.animation_outtime = 0;
247 }
248
249 form.updateGroups();
250 form.updateEventListeners();
251 form.displayFields();
252
253 // bring form in initial state if the reset event is fired on it.
254 // (CF7 triggers the 'reset' event by default on each successfully submitted form)
255 form.$form.on('reset.wpcf7cf', form, function(e) {
256 const form = e.data;
257 setTimeout(function(){
258 form.reloadSimpleDom();
259 form.displayFields();
260 form.resetRepeaters();
261 if (form.multistep != null) {
262 form.multistep.moveToStep(1, false);
263 }
264 setTimeout(function(){
265 if (form.$form.hasClass('sent')) {
266 jQuery('.wpcf7-response-output', form.$form)[0].scrollIntoView({behavior: "smooth", block:"nearest", inline:"nearest"});
267 }
268 }, 400);
269 },200);
270 });
271
272
273
274 }
275
276 /**
277 * reset initial number of subs for each repeater.
278 * (does not clear values)
279 */
280 Wpcf7cfForm.prototype.resetRepeaters = function() {
281 const form = this;
282 form.repeaters.forEach(repeater => {
283 repeater.updateSubs( repeater.params.$repeater.initial_subs );
284 });
285 }
286
287 Wpcf7cfForm.prototype.displayFields = function() {
288
289 const form = this;
290
291 const wpcf7cf_conditions = this.conditions;
292 const wpcf7cf_settings = this.settings;
293
294 //for compatibility with contact-form-7-signature-addon
295 if (cf7signature_resized === 0 &amp;&amp; typeof signatures !== 'undefined' &amp;&amp; signatures.constructor === Array &amp;&amp; signatures.length > 0 ) {
296 for (let i = 0; i &lt; signatures.length; i++) {
297 if (signatures[i].canvas.width === 0) {
298
299 const $sig_canvas = jQuery(".wpcf7-form-control-signature-body>canvas");
300 const $sig_wrap = jQuery(".wpcf7-form-control-signature-wrap");
301 $sig_canvas.eq(i).attr('width', $sig_wrap.width());
302 $sig_canvas.eq(i).attr('height', $sig_wrap.height());
303
304 cf7signature_resized = 1;
305 }
306 }
307 }
308
309 // 'novalidate' makes CF7 skip inline validation inside hidden groups (issue #137)
310 form.$groups.addClass('wpcf7cf-hidden novalidate');
311
312 for (let i=0; i &lt; wpcf7cf_conditions.length; i++) {
313
314 const condition = wpcf7cf_conditions[i];
315
316 const show_group = window.wpcf7cf.should_group_be_shown(condition, form);
317
318 if (show_group) {
319 form.get('[data-id="'+condition.then_field+'"]').removeClass('wpcf7cf-hidden novalidate');
320 }
321 }
322
323
324 const animation_intime = wpcf7cf_settings.animation_intime;
325 const animation_outtime = wpcf7cf_settings.animation_outtime;
326
327 form.$groups.each(function (index) {
328 const $group = jQuery(this);
329 if ($group.is(':animated')) {
330 $group.finish(); // stop any current animations on the group
331 }
332 if ($group.css('display') === 'none' &amp;&amp; !$group.hasClass('wpcf7cf-hidden')) {
333 if ($group.prop('tagName') === 'SPAN') {
334 $group.show().trigger('wpcf7cf_show_group'); // show instantly
335 } else {
336 $group.animate(wpcf7cf_show_animation, animation_intime).trigger('wpcf7cf_show_group'); // show with animation
337 }
338
339 if($group.attr('data-disable_on_hide') !== undefined) {
340 $group.find(':input').prop('disabled', false).trigger('changedisabledprop.wpcf7cf');
341 $group.find('.wpcf7-form-control-wrap').removeClass('wpcf7cf-disabled');
342 }
343
344 } else if ($group.css('display') !== 'none' &amp;&amp; $group.hasClass('wpcf7cf-hidden')) {
345
346 if ($group.attr('data-clear_on_hide') !== undefined) {
347 const $inputs = jQuery(':input', $group).not(':button, :submit, :reset, :hidden');
348
349 $inputs.each(function(){
350 const $this = jQuery(this);
351 $this.val(this.defaultValue);
352 $this.prop('checked', this.defaultChecked);
353 });
354
355 jQuery('option', $group).each(function() {
356 this.selected = this.defaultSelected;
357 });
358
359 jQuery('select', $group).each(function() {
360 const $select = jQuery(this);
361 if ($select.val() === null) {
362 $select.val(jQuery("option:first",$select).val());
363 }
364 });
365
366 $inputs.each(function(){this.dispatchEvent(new Event("change",{"bubbles":true}))});
367 }
368
369 if ($group.prop('tagName') === 'SPAN') {
370 $group.hide().trigger('wpcf7cf_hide_group');
371 } else {
372 $group.animate(wpcf7cf_hide_animation, animation_outtime).trigger('wpcf7cf_hide_group'); // hide
373 }
374 }
375 });
376
377 form.updateHiddenFields();
378
379 form.updateSummaryFields();
380 };
381
382
383
384 Wpcf7cfForm.prototype.updateSummaryFields = function() {
385 const form = this;
386 const $summary = form.get('.wpcf7cf-summary');
387
388 if ($summary.length == 0 || !$summary.is(':visible')) {
389 return;
390 }
391
392 const fd = new FormData();
393
394 const formdata = form.$form.serializeArray();
395 jQuery.each(formdata,function(key, input){
396 fd.append(input.name, input.value);
397 });
398
399 // Make sure to add file fields to FormData
400 jQuery.each(form.$form.find('input[type="file"]'), function(index, el) {
401 if (! el.files.length) return true; // continue
402 const fieldName = el.name;
403 fd.append(fieldName, new Blob() , Array.from(el.files).map(file => file.name).join(', '));
404 });
405
406 // add file fields to form-data
407
408 jQuery.ajax({
409 url: wpcf7cf_global_settings.ajaxurl + '?action=wpcf7cf_get_summary',
410 type: 'POST',
411 data: fd,
412 processData: false,
413 contentType: false,
414 dataType: 'json',
415 success: function(json) {
416 $summary.html(json.summaryHtml);
417 }
418 });
419 };
420
421 Wpcf7cfForm.prototype.updateHiddenFields = function() {
422
423 const form = this;
424
425 const hidden_fields = [];
426 const hidden_groups = [];
427 const visible_groups = [];
428
429 form.$groups.each(function () {
430 const $group = jQuery(this);
431 if ($group.hasClass('wpcf7cf-hidden')) {
432 hidden_groups.push($group.attr('data-id'));
433 if($group.attr('data-disable_on_hide') !== undefined) {
434 // fields inside hidden disable_on_hide group
435 $group.find('input,select,textarea').each(function(){
436 const $this = jQuery(this);
437 if (!$this.prop('disabled')) {
438 $this.prop('disabled', true).trigger('changedisabledprop.wpcf7cf');
439 }
440
441 // if there's no other field with the same name visible in the form
442 // then push this field to hidden_fields
443 if (form.$form.find(`[data-class="wpcf7cf_group"]:not(.wpcf7cf-hidden) [name='${$this.attr('name')}']`).length === 0) {
444 hidden_fields.push($this.attr('name'));
445 }
446 })
447 $group.find('.wpcf7-form-control-wrap').addClass('wpcf7cf-disabled');
448 } else {
449 // fields inside regular hidden group are all pushed to hidden_fields
450 $group.find('input,select,textarea').each(function () {
451 hidden_fields.push(jQuery(this).attr('name'));
452 });
453 }
454 } else {
455 visible_groups.push($group.attr('data-id'));
456 }
457 });
458
459 form.hidden_fields = hidden_fields;
460 form.hidden_groups = hidden_groups;
461 form.visible_groups = visible_groups;
462
463 form.$input_hidden_group_fields.val(JSON.stringify(hidden_fields));
464 form.$input_hidden_groups.val(JSON.stringify(hidden_groups));
465 form.$input_visible_groups.val(JSON.stringify(visible_groups));
466
467 return true;
468 };
469 Wpcf7cfForm.prototype.updateGroups = function() {
470 const form = this;
471 form.$groups = form.$form.find('[data-class="wpcf7cf_group"]');
472 form.$groups.height('auto');
473 form.conditions = window.wpcf7cf.get_nested_conditions(form);
474
475 };
476 Wpcf7cfForm.prototype.updateEventListeners = function() {
477
478 const form = this;
479
480 // monitor input changes, and call displayFields() if something has changed
481 form.get('input, select, textarea, button').not('.wpcf7cf_add, .wpcf7cf_remove').off(wpcf7cf_change_events).on(wpcf7cf_change_events,form, function(e) {
482 window.wpcf7cf_updatingGroups = true; // while this is true, don't allow the form to be submitted.
483 const form = e.data;
484 clearTimeout(wpcf7cf_timeout);
485 wpcf7cf_timeout = setTimeout(function() {
486 window.wpcf7cf.updateMultistepState(form.multistep);
487 form.updateSimpleDom();
488 form.displayFields();
489 window.wpcf7cf_updatingGroups = false;
490 }, wpcf7cf_change_time_ms);
491 });
492
493
494 };
495
496
497
498 // matches an ISO date (YYYY-MM-DD) as submitted by CF7's [date] field
499 const wpcf7cf_date_regex = /^\d{4}-\d{2}-\d{2}$/;
500 function wpcf7cf_isDateString(v) {
501 return typeof v === 'string' &amp;&amp; wpcf7cf_date_regex.test(v) &amp;&amp; !isNaN(Date.parse(v));
502 }
503
504 /**
505 * @global
506 * @namespace wpcf7cf
507 */
508 window.wpcf7cf = {
509
510 hideGroup : function($group, animate) {
511
512 },
513
514 showGroup : function($group, animate) {
515
516 },
517
518 updateRepeaterSubHTML : function(html, oldSuffix, newSuffix, parentRepeaters) {
519 const oldIndexes = oldSuffix.split('__');
520 oldIndexes.shift(); // remove first empty element
521 const newIndexes = newSuffix.split('__');
522 newIndexes.shift(); // remove first empty element
523
524 let returnHtml = html;
525
526 if (
527 oldIndexes &amp;&amp; newIndexes &amp;&amp;
528 oldIndexes.length === parentRepeaters.length &amp;&amp;
529 newIndexes.length === parentRepeaters.length
530 ) {
531
532 const parentRepeatersInfo = parentRepeaters.map((repeaterId, i) => {
533 return {[repeaterId.split('__')[0]]: [oldIndexes[i], newIndexes[i]]};
534 });
535
536 const length = parentRepeatersInfo.length;
537
538 let replacements = oldIndexes.map( (oldIndex, i) => {
539 return [
540 '__'+oldIndexes.slice(0,length-i).join('__'),
541 '__'+newIndexes.slice(0,length-i).join('__'),
542 ];
543 });
544
545
546 for (let i=0; i&lt;length ; i++) {
547 const id = Object.keys(parentRepeatersInfo[i])[0];
548 const find = parentRepeatersInfo[i][id][0];
549 const repl = parentRepeatersInfo[i][id][1];
550 replacements.push([
551 `&lt;span class="wpcf7cf-index wpcf7cf__${id}">${find}&lt;\\/span>`,
552 `&lt;span class="wpcf7cf-index wpcf7cf__${id}">${repl}&lt;/span>`
553 ]);
554 }
555
556 replacements.forEach( ([oldSuffix, newSuffix]) => {
557 returnHtml = returnHtml.replace(new RegExp(oldSuffix,'g'), newSuffix);
558 });
559
560 }
561
562 return returnHtml ;
563 },
564
565 // keep this for backwards compatibility
566 initForm : function($forms) {
567 $forms.each(function(){
568 const formElement = this;
569 // only add form is its class is "wpcf7-form" and if the form was not previously added
570 if (
571 formElement.classList.contains('wpcf7-form') &amp;&amp;
572 !wpcf7cf_forms.some((form)=>{ return form.$form.get(0) === formElement; })
573 ) {
574 wpcf7cf_forms.push(new Wpcf7cfForm(formElement));
575 }
576 });
577 },
578
579 getWpcf7cfForm : function ($form) {
580 const matched_forms = wpcf7cf_forms.filter((form)=>{
581 return form.$form.get(0) === $form.get(0);
582 });
583 if (matched_forms.length) {
584 return matched_forms[0];
585 }
586 return false;
587 },
588
589 get_nested_conditions : function(form) {
590 const conditions = form.initial_conditions;
591 //loop trough conditions. Then loop trough the dom, and each repeater we pass we should update all sub_values we encounter with __index
592 form.reloadSimpleDom();
593 const groups = Object.values(form.simpleDom).filter(function(item, i) {
594 return item.type==='group';
595 });
596
597 let sub_conditions = [];
598
599 for(let i = 0; i &lt; groups.length; i++) {
600 const g = groups[i];
601 let relevant_conditions = conditions.filter(function(condition, i) {
602 return condition.then_field === g.original_name;
603 });
604
605 relevant_conditions = relevant_conditions.map(function(item,i) {
606 return {
607 then_field : g.name,
608 and_rules : item.and_rules.map(function(and_rule, i) {
609 return {
610 if_field : and_rule.if_field+g.suffix,
611 if_value : and_rule.if_value,
612 operator : and_rule.operator
613 };
614 })
615 }
616 });
617
618 sub_conditions = sub_conditions.concat(relevant_conditions);
619 }
620 return sub_conditions;
621 },
622
623 get_simplified_dom_model : function(currentNode, simplified_dom = {}, parentGroups = [], parentRepeaters = []) {
624
625
626 const type = currentNode.classList &amp;&amp; currentNode.classList.contains('wpcf7cf_repeater') ? 'repeater' :
627 currentNode.dataset.class == 'wpcf7cf_group' ? 'group' :
628 currentNode.className == 'wpcf7cf_step' ? 'step' :
629 currentNode.hasAttribute('name') ? 'input' : false;
630
631 let newParentRepeaters = [...parentRepeaters];
632 let newParentGroups = [...parentGroups];
633
634 if (type) {
635
636 const name = type === 'input' ? currentNode.getAttribute('name') : currentNode.dataset.id;
637
638 if (type === 'repeater') {
639 newParentRepeaters.push(name);
640 }
641 if (type === 'group') {
642 newParentGroups.push(name);
643 }
644
645 // skip _wpcf7 hidden fields
646 if (name.substring(0,6) === '_wpcf7') return {};
647
648 const original_name = type === 'repeater' || type === 'group' ? currentNode.dataset.orig_data_id
649 : type === 'input' ? (currentNode.getAttribute('data-orig_name') || name)
650 : name;
651
652 const nameWithoutBrackets = name.replace('[]','');
653 const originalNameWithoutBrackets = original_name.replace('[]','');
654
655 const val = type === 'step' ? [currentNode.dataset.id.substring(5)] : [];
656
657 const suffix = nameWithoutBrackets.replace(originalNameWithoutBrackets, '');
658
659 if (!simplified_dom[name]) {
660 // init entry
661 simplified_dom[name] = {name, type, original_name, suffix, val, parentGroups, parentRepeaters}
662 }
663
664 if (type === 'input') {
665
666 // skip unchecked checkboxes and radiobuttons
667 if ( (currentNode.type === 'checkbox' || currentNode.type === 'radio') &amp;&amp; !currentNode.checked ) return {};
668
669 // if multiselect, make sure to add all the values
670 if ( currentNode.multiple &amp;&amp; currentNode.options ) {
671 simplified_dom[name].val = Object.values(currentNode.options).filter(o => o.selected).map(o => o.value)
672 } else {
673 simplified_dom[name].val.push(currentNode.value);
674 }
675 }
676 }
677
678 // can't use currentNode.children (because then field name cannot be "children")
679 const getter = Object.getOwnPropertyDescriptor(Element.prototype, "children").get;
680 const children = getter.call(currentNode);
681
682 Array.from(children).forEach(childNode => {
683 const dom = wpcf7cf.get_simplified_dom_model(childNode, simplified_dom, newParentGroups, newParentRepeaters);
684 simplified_dom = {...dom, ...simplified_dom} ;
685 });
686
687 return simplified_dom;
688 },
689
690 updateMultistepState: function (multistep) {
691 if (multistep == null) return;
692 if (multistep.form.$form.hasClass('submitting')) return;
693
694 // update hidden input field
695
696 const stepsData = {
697 currentStep : multistep.currentStep,
698 numSteps : multistep.numSteps,
699 fieldsInCurrentStep : multistep.getFieldsInStep(multistep.currentStep)
700 };
701 multistep.form.$input_steps.val(JSON.stringify(stepsData));
702
703 // update Buttons
704 multistep.$btn_prev.removeClass('disabled').attr('disabled', false);
705 multistep.$btn_next.removeClass('disabled').attr('disabled', false);
706 if (multistep.currentStep == multistep.numSteps) {
707 multistep.$btn_next.addClass('disabled').attr('disabled', true);
708 }
709 if (multistep.currentStep == 1) {
710 multistep.$btn_prev.addClass('disabled').attr('disabled', true);
711 }
712
713 const $current_step = multistep.$steps.eq(multistep.currentStep - 1);
714 const prev_text = $current_step.attr('data-prev-button-text');
715 const next_text = $current_step.attr('data-next-button-text');
716 if (prev_text !== undefined) multistep.$btn_prev.text(prev_text);
717 if (next_text !== undefined) multistep.$btn_next.text(next_text);
718
719 // replace next button with submit button on last step.
720 // TODO: make this depend on a setting
721 const $submit_button = multistep.form.$form.find('input[type="submit"]:last').eq(0);
722 const $ajax_loader = multistep.form.$form.find('.wpcf7-spinner').eq(0);
723
724 $submit_button.detach().prependTo(multistep.$btn_next.parent());
725 $ajax_loader.detach().prependTo(multistep.$btn_next.parent());
726
727 if (multistep.currentStep == multistep.numSteps) {
728 multistep.$btn_next.hide();
729 $submit_button.show();
730 } else {
731 $submit_button.hide();
732 multistep.$btn_next.show();
733 }
734
735 // update dots
736 const $dots = multistep.$dots.find('.dot');
737 $dots.removeClass('active').removeClass('completed');
738 for(let step = 1; step &lt;= multistep.numSteps; step++) {
739 if (step &lt; multistep.currentStep) {
740 $dots.eq(step-1).addClass('completed');
741 } else if (step == multistep.currentStep) {
742 $dots.eq(step-1).addClass('active');
743 }
744 }
745
746 },
747
748 should_group_be_shown : function(condition, form) {
749
750 let show_group = true;
751 let atLeastOneFieldFound = false;
752
753 for (let and_rule_i = 0; and_rule_i &lt; condition.and_rules.length; and_rule_i++) {
754
755 let condition_ok = false;
756
757 const condition_and_rule = condition.and_rules[and_rule_i];
758
759 const inputField = form.getFieldByName(condition_and_rule.if_field);
760
761 if (!inputField) continue; // field not found
762
763 atLeastOneFieldFound = true;
764
765 const if_val = condition_and_rule.if_value;
766 let operator = condition_and_rule.operator;
767
768 //backwards compat
769 operator = operator === '≤' ? 'less than or equals' : operator;
770 operator = operator === '≥' ? 'greater than or equals' : operator;
771 operator = operator === '>' ? 'greater than' : operator;
772 operator = operator === '&lt;' ? 'less than' : operator;
773
774 const $field = operator === 'function' &amp;&amp; jQuery(`[name="${inputField.name}"]`).eq(0);
775
776 condition_ok = this.isConditionTrue(inputField.val,operator,if_val, $field);
777
778 show_group = show_group &amp;&amp; condition_ok;
779 }
780
781 return show_group &amp;&amp; atLeastOneFieldFound;
782
783 },
784
785 isConditionTrue(values, operator, testValue='', $field=jQuery()) {
786
787 if (!Array.isArray(values)) {
788 values = [values];
789 }
790
791 let condition_ok = false; // start by assuming that the condition is not met
792
793 // Considered EMPTY: [] [''] [null] ['',null] [,,'']
794 // Considered NOT EMPTY: [0] ['ab','c'] ['',0,null]
795 const valuesAreEmpty = values.length === 0 || values.every((v) => !v&amp;&amp;v!==0); // 0 is not considered empty
796
797 // special cases: [] equals '' => TRUE; [] not equals '' => FALSE
798 if (operator === 'equals' &amp;&amp; testValue === '' &amp;&amp; valuesAreEmpty) {
799 return true;
800 }
801 if (operator === 'not equals' &amp;&amp; testValue === '' &amp;&amp; valuesAreEmpty) {
802 return false;
803 }
804
805 if (valuesAreEmpty) {
806 if (operator === 'is empty') {
807 condition_ok = true;
808 }
809 } else {
810 if (operator === 'not empty') {
811 condition_ok = true;
812 }
813 }
814
815 const testValueNumber = isFinite(parseFloat(testValue)) ? parseFloat(testValue) : NaN;
816 const testValueIsDate = wpcf7cf_isDateString(testValue);
817
818
819 if (operator === 'not equals' || operator === 'not equals (regex)') {
820 // start by assuming that the condition is met
821 condition_ok = true;
822 }
823
824 if (
825 operator === 'function'
826 &amp;&amp; typeof window[testValue] == 'function'
827 &amp;&amp; window[testValue]($field) // here we call the actual user defined function
828 ) {
829 condition_ok = true;
830 }
831
832 let regex_patt = /.*/i; // fallback regex pattern
833 let isValidRegex = true;
834 if (operator === 'equals (regex)' || operator === 'not equals (regex)') {
835 try {
836 regex_patt = new RegExp(testValue, 'i');
837 } catch(e) {
838 isValidRegex = false;
839 }
840 }
841
842
843 for(let i = 0; i &lt; values.length; i++) {
844
845 const value = values[i];
846
847 const valueNumber = isFinite(parseFloat(value)) ? parseFloat(value) : NaN;
848 const valsAreNumbers = !isNaN(valueNumber) &amp;&amp; !isNaN(testValueNumber);
849
850 // when both sides are ISO dates, compare chronologically instead of by parseFloat (which reads only the year)
851 const valueIsDate = wpcf7cf_isDateString(value);
852 const compareAsDates = testValueIsDate &amp;&amp; valueIsDate;
853 const left = compareAsDates ? Date.parse(value) : valueNumber;
854 const right = compareAsDates ? Date.parse(testValue) : testValueNumber;
855 // a date on one side and a plain number on the other are not comparable
856 const comparable = compareAsDates || (valsAreNumbers &amp;&amp; testValueIsDate === valueIsDate);
857
858 if (
859
860 operator === 'equals' &amp;&amp; value === testValue ||
861 operator === 'equals (regex)' &amp;&amp; regex_patt.test(value) ||
862 operator === 'greater than' &amp;&amp; comparable &amp;&amp; left > right ||
863 operator === 'less than' &amp;&amp; comparable &amp;&amp; left &lt; right ||
864 operator === 'greater than or equals' &amp;&amp; comparable &amp;&amp; left >= right ||
865 operator === 'less than or equals' &amp;&amp; comparable &amp;&amp; left &lt;= right
866
867 ) {
868
869 condition_ok = true;
870 break;
871
872 } else if (
873
874 operator === 'not equals' &amp;&amp; value === testValue ||
875 operator === 'not equals (regex)' &amp;&amp; regex_patt.test(value)
876
877 ) {
878
879 condition_ok = false;
880 break;
881
882 }
883 }
884
885 return condition_ok;
886
887 },
888
889 getFormObj($form) {
890 if (typeof $form === 'string') {
891 $form = jQuery($form).eq(0);
892 }
893 return wpcf7cf.getWpcf7cfForm($form);
894 },
895
896 getRepeaterObj($form, repeaterDataId) {
897 const form = wpcf7cf.getFormObj($form);
898 const repeater = form.repeaters.find( repeater => repeater.params.$repeater.attr('data-id') === repeaterDataId );
899
900 return repeater;
901
902 },
903
904 getMultiStepObj($form){
905 const form = wpcf7cf.getFormObj($form);
906 return form.multistep;
907 },
908
909 /**
910 * Append a new sub-entry to the repeater with the name `repeaterDataId` inside the form `$form`
911 * @memberof wpcf7cf
912 * @function wpcf7cf.repeaterAddSub
913 * @link
914 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
915 * @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)
916 */
917 repeaterAddSub($form,repeaterDataId) {
918 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
919 repeater.updateSubs(repeater.params.$repeater.num_subs+1);
920 },
921
922 /**
923 * Insert a new sub-entry at the given `index` of the repeater with the name `repeaterDataId` inside the form `$form`
924 * @memberof wpcf7cf
925 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
926 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
927 * @param {Number} index - position where to insert the new sub-entry within the repeater
928 */
929 repeaterAddSubAtIndex($form,repeaterDataId,index) {
930 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
931 repeater.addSubs(1, index);
932 },
933
934 /**
935 * Remove the sub-entry at the given `index` of the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`
936 * @memberof wpcf7cf
937 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
938 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
939 * @param {Number} index - position where to insert the new sub-entry within the repeater
940 */
941 repeaterRemoveSubAtIndex($form,repeaterDataId,index) {
942 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
943 repeater.removeSubs(1, index);
944 },
945
946 /**
947 * Remove the last sub-entry from the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`
948 * @memberof wpcf7cf
949 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
950 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
951 * @param {Number} index - position where to insert the new sub-entry within the repeater
952 */
953 repeaterRemoveSub($form,repeaterDataId) {
954 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
955 repeater.updateSubs(repeater.params.$repeater.num_subs-1);
956 },
957
958 /**
959 * Set the number of subs for the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`.
960 * Subs are either appended to or removed from the end of the repeater.
961 * @memberof wpcf7cf
962 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
963 * @param {String} repeaterDataId - *data-id* attribute of the repeater.
964 * @param {Number} numberOfSubs - position where to insert the new sub-entry within the repeater
965 */
966 repeaterSetNumberOfSubs($form, repeaterDataId, numberOfSubs) {
967 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId);
968 repeater.updateSubs(numberOfSubs);
969 },
970
971 /**
972 * Move to step number `step`, ignoring any validation.
973 * @memberof wpcf7cf
974 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
975 * @param {*} step
976 */
977 multistepMoveToStep($form, step) {
978 const multistep = wpcf7cf.getMultiStepObj($form);
979 multistep.moveToStep(step);
980 },
981
982 /**
983 * Validate the current step, and move to step number `step` if validation passes.
984 * @memberof wpcf7cf
985 * @param {String|JQuery} $form - JQuery object or css-selector representing the form
986 * @param {Number} step
987 */
988 async multistepMoveToStepWithValidation($form, step) {
989 const multistep = wpcf7cf.getMultiStepObj($form);
990
991 const result = await multistep.validateStep(multistep.currentStep);
992 if (result === 'success') {
993 multistep.moveToStep(step);
994 }
995 },
996
997
998
999 };
1000
1001 document.querySelectorAll('.wpcf7-form').forEach(function(formElement){
1002 wpcf7cf_forms.push(new Wpcf7cfForm(formElement));
1003 });
1004
1005 // Call displayFields again on all forms
1006 // Necessary in case some theme or plugin changed a form value by the time the entire page is fully loaded.
1007 document.addEventListener('DOMContentLoaded', function () {
1008 wpcf7cf_forms.forEach(function(f){
1009 f.displayFields();
1010 });
1011 });</code></pre>
1012 </article>
1013 </section>
1014
1015
1016
1017
1018 </div>
1019
1020 <nav>
1021 <h2><a href="index.html">Home</a></h2><h3>Namespaces</h3><ul><li><a href="wpcf7cf.html">wpcf7cf</a></li></ul><h3>Global</h3><ul><li><a href="global.html#all">all</a></li><li><a href="global.html#get">get</a></li><li><a href="global.html#raw">raw</a></li><li><a href="global.html#suffix">suffix</a></li><li><a href="global.html#sum">sum</a></li></ul>
1022 </nav>
1023
1024 <br class="clear">
1025
1026 <footer>
1027 Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.2</a> on Tue Jul 07 2026 03:19:09 GMT+0200 (Central European Summer Time)
1028 </footer>
1029
1030 <script> prettyPrint(); </script>
1031 <script src="scripts/linenumber.js"> </script>
1032 </body>
1033 </html>
1034