PluginProbe
Formidable Forms – WordPress Form Builder for Contact Forms, Calculators, Quizzes & More / trunk
Formidable Forms – WordPress Form Builder for Contact Forms, Calculators, Quizzes & More vtrunk
6.35 6.34 6.33.1 6.33 6.32.1 6.32 6.31 6.25 6.25.1 6.26 6.26.1 6.27 6.28 6.29 6.3 6.3.1 6.3.2 6.30 6.4 6.4.1 6.4.2 6.5 6.5.1 6.5.2 6.5.3 All 141 releases
← All changes | js/formidable.js +857 -380 6.25.1 → trunk View file →
@@ -1,13 +1,9 @@
1 1 /* exported frmRecaptcha, frmAfterRecaptcha */
2 -/* eslint-disable prefer-const */
3 2
4 3 function frmFrontFormJS() {
5 4 'use strict';
6 5
7 - /*global jQuery:false, frm_js, grecaptcha, hcaptcha, turnstile, frmProForm, tinyMCE */
8 - /*global frmThemeOverride_jsErrors, frmThemeOverride_frmPlaceError, frmThemeOverride_frmAfterSubmit */
9 -
10 6 let jsErrors = [];
11 7
12 8 /**
13 9 * Triggers custom JS event.
@@ -36,29 +32,27 @@
36 32 * @param {boolean} fullID
37 33 * @return {string|number} Field ID.
38 34 */
39 35 function getFieldId( field, fullID ) {
40 - let nameParts, fieldId,
41 - isRepeating = false,
42 - fieldName = '';
36 + let nameParts;
37 + let fieldId;
38 + let isRepeating = false;
39 + let fieldName = '';
40 +
43 41 if ( field instanceof jQuery ) {
44 - fieldName = field.attr( 'name' );
45 - } else {
46 - fieldName = field.name;
42 + field = field.get( 0 );
47 43 }
48 44
49 - if ( typeof fieldName === 'undefined' ) {
45 + fieldName = field.name;
46 +
47 + if ( fieldName === undefined ) {
50 48 fieldName = '';
51 49 }
52 50
53 51 if ( fieldName === '' ) {
54 - if ( field instanceof jQuery ) {
55 - fieldName = field.data( 'name' );
56 - } else {
57 - fieldName = field.getAttribute( 'data-name' );
58 - }
52 + fieldName = field.getAttribute( 'data-name' );
59 53
60 - if ( typeof fieldName === 'undefined' ) {
54 + if ( fieldName === undefined ) {
61 55 fieldName = '';
62 56 }
63 57
64 58 if ( fieldName !== '' && fieldName ) {
@@ -86,9 +80,9 @@
86 80 return 0;
87 81 }
88 82
89 83 // Check if 'this' is in a repeating section
90 - if ( document.querySelector( 'input[name="item_meta[' + fieldId + '][form]"]' ) ) {
84 + if ( document.querySelector( `input[name="item_meta[${ fieldId }][form]"]` ) ) {
91 85 // this is a repeatable section with name: item_meta[repeating-section-id][row-id][field-id]
92 86 fieldId = nameParts[ 2 ].replace( '[', '' );
93 87 isRepeating = true;
94 88 }
@@ -106,11 +100,11 @@
106 100
107 101 if ( fullID === true ) {
108 102 // For use in the container div id
109 103 if ( fieldId === nameParts[ 0 ] ) {
110 - fieldId = fieldId + '-' + nameParts[ 1 ].replace( '[', '' );
104 + fieldId = `${ fieldId }-${ nameParts[ 1 ].replace( '[', '' ) }`;
111 105 } else {
112 - fieldId = fieldId + '-' + nameParts[ 0 ] + '-' + nameParts[ 1 ].replace( '[', '' );
106 + fieldId = `${ fieldId }-${ nameParts[ 0 ] }-${ nameParts[ 1 ].replace( '[', '' ) }`;
113 107 }
114 108 }
115 109
116 110 return fieldId;
@@ -123,9 +117,15 @@
123 117 *
124 118 * @param {Object} $form
125 119 */
126 120 function disableSubmitButton( $form ) {
127 - $form.find( 'input[type="submit"], input[type="button"], button[type="submit"], button.frm_save_draft' ).attr( 'disabled', 'disabled' );
121 + const form = $form instanceof jQuery ? $form.get( 0 ) : $form;
122 + if ( ! form ) {
123 + return;
124 + }
125 + form.querySelectorAll( 'input[type="submit"], input[type="button"], button[type="submit"], button.frm_save_draft' ).forEach(
126 + button => button.disabled = true
127 + );
128 128 }
129 129
130 130 /**
131 131 * Enable the submit button for a given jQuery form object
@@ -131,12 +131,16 @@
131 131 * Enable the submit button for a given jQuery form object
132 132 *
133 133 * @since 2.03.02
134 134 *
135 - * @param {Object} $form
135 + * @param {HTMLElement} form
136 + *
137 + * @return {void}
136 138 */
137 - function enableSubmitButton( $form ) {
138 - $form.find( 'input[type="submit"], input[type="button"], button[type="submit"]' ).prop( 'disabled', false );
139 + function enableSubmitButton( form ) {
140 + form.querySelectorAll( 'input[type="submit"], input[type="button"], button[type="submit"]' ).forEach(
141 + button => button.disabled = false
142 + );
139 143 }
140 144
141 145 /**
142 146 * Disable the save draft link for a given jQuery form object
@@ -145,23 +149,30 @@
145 149 *
146 150 * @param {Object} $form
147 151 */
148 152 function disableSaveDraft( $form ) {
149 - $form.find( 'a.frm_save_draft' ).css( 'pointer-events', 'none' );
153 + const form = $form instanceof jQuery ? $form.get( 0 ) : $form;
154 + if ( ! form ) {
155 + return;
156 + }
157 + form.querySelectorAll( 'a.frm_save_draft' ).forEach(
158 + link => link.style.pointerEvents = 'none'
159 + );
150 160 }
151 161
152 162 /**
153 - * Enable the save draft link for a given jQuery form object
163 + * Enable the save draft link for a given form object.
154 164 *
155 165 * @since 4.04.03
156 166 *
157 - * @param {jQuery} $form
167 + * @param {jQuery|HTMLElement} $form
158 168 */
159 169 function enableSaveDraft( $form ) {
160 - if ( ! $form.length ) {
170 + const form = $form instanceof jQuery ? $form.get( 0 ) : $form;
171 + if ( ! form ) {
161 172 return;
162 173 }
163 - $form[ 0 ].querySelectorAll( '.frm_save_draft' ).forEach( saveDraftButton => {
174 + form.querySelectorAll( '.frm_save_draft' ).forEach( saveDraftButton => {
164 175 saveDraftButton.disabled = false;
165 176 saveDraftButton.style.pointerEvents = '';
166 177 } );
167 178 }
@@ -236,15 +247,14 @@
236 247 * @param {Array} errors
237 248 * @return {void}
238 249 */
239 250 function checkValidity( field, errors ) {
240 - let fieldID;
241 251 if ( 'object' !== typeof field.validity || false !== field.validity.valid ) {
242 252 return;
243 253 }
244 254
245 - fieldID = getFieldId( field, true );
246 - if ( 'undefined' === typeof errors[ fieldID ] ) {
255 + const fieldID = getFieldId( field, true );
256 + if ( errors[ fieldID ] === undefined ) {
247 257 errors[ fieldID ] = getFieldValidationMessage( field, 'data-invmsg' );
248 258 }
249 259
250 260 if ( 'function' === typeof field.reportValidity ) {
@@ -271,11 +281,14 @@
271 281 if ( field.type === 'url' ) {
272 282 maybeAddHttpsToUrl( field );
273 283 }
274 284 const form = field.closest( 'form' );
275 - if ( form && hasClass( form, 'frm_js_validate' ) ) {
276 - validateField( field );
285 + if ( ! form ) {
286 + return;
277 287 }
288 +
289 + // Removing stale errors is universal. Adding errors only happens when JS validation is enabled.
290 + validateField( field, hasClass( form, 'frm_js_validate' ) );
278 291 }
279 292
280 293 /**
281 294 * @param {HTMLElement} field
@@ -283,9 +296,9 @@
283 296 function maybeAddHttpsToUrl( field ) {
284 297 const url = field.value;
285 298 const matches = url.match( /^(https?|ftps?|mailto|news|feed|telnet):/ );
286 299 if ( field.value !== '' && matches === null ) {
287 - field.value = 'https://' + url;
300 + field.value = `https://${ url }`;
288 301 }
289 302 }
290 303
291 304 /**
@@ -290,14 +303,20 @@
290 303
291 304 /**
292 305 * Validate a field with JS.
293 306 *
307 + * Removing stale errors is universal. Adding errors only happens when JS validation is enabled.
308 + *
309 + * @since 6.32 Added the `addErrors` parameter.
310 + *
294 311 * @param {HTMLElement} field
312 + * @param {boolean} addErrors Whether to add new errors. Defaults to `true`.
295 313 *
296 314 * @return {void}
297 315 */
298 - function validateField( field ) {
299 - let errors, key;
316 + function validateField( field, addErrors = true ) {
317 + let errors;
318 + let key;
300 319
301 320 errors = [];
302 321 const fieldContainer = field.closest( '.frm_form_field' );
303 322
@@ -313,14 +332,20 @@
313 332 if ( errors.length < 1 ) {
314 333 validateFieldValue( field, errors, false );
315 334 }
316 335
317 - const $fieldCont = jQuery( fieldContainer );
318 - removeFieldError( $fieldCont );
319 - if ( Object.keys( errors ).length > 0 ) {
320 - for ( key in errors ) {
321 - addFieldError( $fieldCont, key, errors );
336 + const hasErrors = Object.keys( errors ).length > 0;
337 +
338 + if ( addErrors ) {
339 + removeFieldError( fieldContainer );
340 + if ( hasErrors ) {
341 + for ( key in errors ) {
342 + addFieldError( fieldContainer, key, errors );
343 + }
322 344 }
345 + } else if ( ! hasErrors ) {
346 + // JS validation is off, so only remove existing errors once the field passes validation.
347 + removeFieldError( fieldContainer );
323 348 }
324 349 }
325 350
326 351 /**
@@ -354,11 +379,11 @@
354 379 /**
355 380 * @since 6.15 Added `onSubmit` to the data.
356 381 */
357 382 triggerCustomEvent( document, 'frm_validate_field_value', {
358 - field: field,
359 - errors: errors,
360 - onSubmit: onSubmit
383 + field,
384 + errors,
385 + onSubmit
361 386 } );
362 387 }
363 388
364 389 /**
@@ -366,12 +391,14 @@
366 391 * @param {Array} errors
367 392 * @return {Array} Errors
368 393 */
369 394 function checkRequiredField( field, errors ) {
370 - let tempVal, i, placeholder,
371 - val = '',
372 - fieldID = '',
373 - fileID = field.getAttribute( 'data-frmfile' );
395 + let tempVal;
396 + let i;
397 + let placeholder;
398 + let val = '';
399 + let fieldID = '';
400 + let fileID = field.getAttribute( 'data-frmfile' );
374 401
375 402 if ( field.type === 'hidden' && fileID === null && ! isAppointmentField( field ) && ! isInlineDatepickerField( field ) ) {
376 403 return errors;
377 404 }
@@ -376,9 +403,9 @@
376 403 return errors;
377 404 }
378 405
379 406 if ( field.type === 'checkbox' || field.type === 'radio' ) {
380 - document.querySelectorAll( 'input[name="' + field.name + '"]' ).forEach( function( input ) {
407 + document.querySelectorAll( `input[name="${ field.name }"]` ).forEach( function( input ) {
381 408 const requiredField = input.closest( '.frm_required_field' );
382 409 if ( ! requiredField ) {
383 410 return;
384 411 }
@@ -388,14 +415,14 @@
388 415 val = checkedInput.value;
389 416 } );
390 417 } );
391 418 } else if ( field.type === 'file' || fileID ) {
392 - if ( typeof fileID === 'undefined' ) {
419 + if ( fileID === undefined ) {
393 420 fileID = getFieldId( field, true );
394 421 fileID = fileID.replace( 'file', '' );
395 422 }
396 423
397 - if ( typeof errors[ fileID ] === 'undefined' ) {
424 + if ( errors[ fileID ] === undefined ) {
398 425 val = getFileVals( fileID );
399 426 }
400 427 fieldID = fileID;
401 428 } else {
@@ -403,9 +430,10 @@
403 430 // skip hidden other fields
404 431 return errors;
405 432 }
406 433
407 - val = jQuery( field ).val();
434 + val = jQuery( field ).val(); // eslint-disable-line no-jquery/no-val
435 +
408 436 if ( val === null ) {
409 437 val = '';
410 438 } else if ( typeof val !== 'string' ) {
411 439 tempVal = val;
@@ -437,9 +465,11 @@
437 465 // set id for time field
438 466 fieldID = fieldID.replace( '-H', '' ).replace( '-m', '' );
439 467 } else if ( isSignatureField( field ) ) {
440 468 if ( val === '' ) {
441 - val = jQuery( field ).closest( '.frm_form_field' ).find( '[name="' + field.getAttribute( 'name' ).replace( '[typed]', '[output]' ) + '"]' ).val();
469 + const fieldContainer = field.closest( '.frm_form_field' );
470 + const outputField = fieldContainer ? fieldContainer.querySelector( `[name="${ field.getAttribute( 'name' ).replace( '[typed]', '[output]' ) }"]` ) : null;
471 + val = outputField ? outputField.value : '';
442 472 }
443 473 fieldID = fieldID.replace( '-typed', '' );
444 474 }
445 475
@@ -490,14 +520,14 @@
490 520 * @param {string|number} fileID
491 521 * @return {string} File input value.
492 522 */
493 523 function getFileVals( fileID ) {
494 - let val = '',
495 - fileFields = jQuery( 'input[name="file' + fileID + '"], input[name="file' + fileID + '[]"], input[name^="item_meta[' + fileID + ']"]' );
524 + let val = '';
525 + const fileFields = document.querySelectorAll( `input[name="file${ fileID }"], input[name="file${ fileID }[]"], input[name^="item_meta[${ fileID }]"]` );
496 526
497 - fileFields.each( function() {
527 + fileFields.forEach( function( field ) {
498 528 if ( val === '' ) {
499 - val = this.value;
529 + val = field.value;
500 530 }
501 531 } );
502 532 return val;
503 533 }
@@ -507,10 +537,10 @@
507 537 * @param {Array} errors
508 538 * @return {void}
509 539 */
510 540 function checkUrlField( field, errors ) {
511 - let fieldID,
512 - url = field.value;
541 + let fieldID;
542 + const url = field.value;
513 543
514 544 if ( url !== '' && ! /^http(s)?:\/\/(?:localhost|(?:[\da-z\.-]+\.[\da-z\.-]+))/i.test( url ) ) {
515 545 fieldID = getFieldId( field, true );
516 546 if ( ! ( fieldID in errors ) ) {
@@ -551,10 +581,10 @@
551 581 * @param {Object} errors Errors data.
552 582 * @param {boolean} onSubmit Is `true` if the form is being submitted.
553 583 */
554 584 function checkEmailField( field, errors, onSubmit ) {
555 - const fieldID = getFieldId( field, true ),
556 - pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
585 + const fieldID = getFieldId( field, true );
586 + const pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
557 587
558 588 // validate the current field we're editing first
559 589 if ( '' !== field.value && pattern.test( field.value ) === false ) {
560 590 errors[ fieldID ] = getFieldValidationMessage( field, 'data-invmsg' );
@@ -585,24 +615,23 @@
585 615 * @param {Array} errors
586 616 * @return {void}
587 617 */
588 618 function confirmField( field, errors ) {
589 - let value, confirmValue, firstField,
590 - fieldID = getFieldId( field, true ),
591 - strippedId = field.id.replace( 'conf_', '' ),
592 - strippedFieldID = fieldID.replace( 'conf_', '' ),
593 - confirmField = document.getElementById( strippedId.replace( 'field_', 'field_conf_' ) );
619 + const fieldID = getFieldId( field, true );
620 + const strippedId = field.id.replace( 'conf_', '' );
621 + const strippedFieldID = fieldID.replace( 'conf_', '' );
622 + const confirmField = document.getElementById( strippedId.replace( 'field_', 'field_conf_' ) );
594 623
595 - if ( confirmField === null || typeof errors[ 'conf_' + strippedFieldID ] !== 'undefined' ) {
624 + if ( ! confirmField || errors[ `conf_${ strippedFieldID }` ] !== undefined ) {
596 625 return;
597 626 }
598 627
599 628 if ( fieldID !== strippedFieldID ) {
600 - firstField = document.getElementById( strippedId );
601 - value = firstField.value;
602 - confirmValue = confirmField.value;
629 + const firstField = document.getElementById( strippedId );
630 + const { value } = firstField;
631 + const confirmValue = confirmField.value;
603 632 if ( value !== confirmValue ) {
604 - errors[ 'conf_' + strippedFieldID ] = getFieldValidationMessage( confirmField, 'data-confmsg' );
633 + errors[ `conf_${ strippedFieldID }` ] = getFieldValidationMessage( confirmField, 'data-confmsg' );
605 634 }
606 635 } else {
607 636 validateField( confirmField );
608 637 }
@@ -613,10 +642,10 @@
613 642 * @param {Array} errors
614 643 * @return {void}
615 644 */
616 645 function checkNumberField( field, errors ) {
617 - let fieldID,
618 - number = field.value;
646 + let fieldID;
647 + const number = field.value;
619 648
620 649 if ( number !== '' && isNaN( number / 1 ) !== false ) {
621 650 fieldID = getFieldId( field, true );
622 651 if ( ! ( fieldID in errors ) ) {
@@ -630,11 +659,11 @@
630 659 * @param {Array} errors
631 660 * @return {void}
632 661 */
633 662 function checkPatternField( field, errors ) {
634 - let fieldID,
635 - text = field.value,
636 - format = getFieldValidationMessage( field, 'pattern' );
663 + let fieldID;
664 + const text = field.value;
665 + let format = getFieldValidationMessage( field, 'pattern' );
637 666
638 667 if ( format !== '' && text !== '' ) {
639 668 fieldID = getFieldId( field, true );
640 669 if ( ! ( fieldID in errors ) ) {
@@ -642,9 +671,9 @@
642 671 if ( ! window.frmProForm.validateIntlPhoneInput( field ) ) {
643 672 errors[ fieldID ] = getFieldValidationMessage( field, 'data-invmsg' );
644 673 }
645 674 } else {
646 - format = new RegExp( '^' + format + '$', 'i' );
675 + format = new RegExp( `^${ format }$`, 'i' );
647 676 if ( format.test( text ) === false ) {
648 677 errors[ fieldID ] = getFieldValidationMessage( field, 'data-invmsg' );
649 678 }
650 679 }
@@ -657,13 +686,11 @@
657 686 *
658 687 * @since 6.5.1
659 688 */
660 689 function setSelectPlaceholderColor() {
661 - let selects = document.querySelectorAll( '.form-field select' ),
662 - styleElement = document.querySelector( '.with_frm_style' ),
663 - textColorDisabled = styleElement ? getComputedStyle( styleElement ).getPropertyValue( '--text-color-disabled' ).trim() : '',
664 - changeSelectColor;
665 -
690 + const selects = document.querySelectorAll( '.form-field select' );
691 + const styleElement = document.querySelector( '.with_frm_style' );
692 + const textColorDisabled = styleElement ? getComputedStyle( styleElement ).getPropertyValue( '--text-color-disabled' ).trim() : '';
666 693 // Exit if there are no select elements or the textColorDisabled property is missing
667 694 if ( ! selects.length || ! textColorDisabled ) {
668 695 return;
669 696 }
@@ -668,9 +695,9 @@
668 695 return;
669 696 }
670 697
671 698 // Function to change the color of a select element
672 - changeSelectColor = function( select ) {
699 + const changeSelectColor = function( select ) {
673 700 if ( select.options[ select.selectedIndex ] && hasClass( select.options[ select.selectedIndex ], 'frm-select-placeholder' ) ) {
674 701 select.style.setProperty( 'color', textColorDisabled, 'important' );
675 702 } else {
676 703 select.style.color = '';
@@ -690,51 +717,62 @@
690 717 }
691 718
692 719 /**
693 720 * @param {HTMLElement|jQuery} object
694 - * @return {boolean} True if there is an invisible recaptcha.
721 + *
722 + * @return {HTMLElement|false} Captcha element if there is an invisible recaptcha.
695 723 */
696 724 function hasInvisibleRecaptcha( object ) {
697 - let recaptcha, recaptchaID, alreadyChecked;
725 + if ( isGoingToPrevPage( object ) ) {
726 + return false;
727 + }
698 728
699 - if ( isGoingToPrevPage( object ) ) {
729 + const form = object instanceof jQuery ? object.get( 0 ) : object;
730 + if ( ! form ) {
700 731 return false;
701 732 }
702 733
703 - recaptcha = jQuery( object ).find( '.frm-g-recaptcha[data-size="invisible"], .g-recaptcha[data-size="invisible"]' );
704 - if ( recaptcha.length ) {
705 - recaptchaID = recaptcha.data( 'rid' );
706 - alreadyChecked = grecaptcha.getResponse( recaptchaID );
734 + const recaptcha = form.querySelector( '.frm-g-recaptcha[data-size="invisible"], .g-recaptcha[data-size="invisible"]' );
735 + if ( recaptcha ) {
736 + const recaptchaID = recaptcha.dataset.rid;
737 + const alreadyChecked = grecaptcha.getResponse( recaptchaID );
707 738 if ( alreadyChecked.length === 0 ) {
708 739 return recaptcha;
709 740 }
710 741 }
742 +
711 743 return false;
712 744 }
713 745
714 746 /**
715 - * @param {jQuery} invisibleRecaptcha
747 + * @param {HTMLElement} invisibleRecaptcha
748 + *
749 + * @return {void}
716 750 */
717 751 function executeInvisibleRecaptcha( invisibleRecaptcha ) {
718 - const recaptchaID = invisibleRecaptcha.data( 'rid' );
752 + const recaptchaID = invisibleRecaptcha.dataset.rid;
719 753 grecaptcha.reset( recaptchaID );
720 754 grecaptcha.execute( recaptchaID );
721 755 }
722 756
723 757 function validateRecaptcha( form, errors ) {
724 - let response;
758 + const formEl = form instanceof jQuery ? form.get( 0 ) : form;
759 + if ( ! formEl ) {
760 + return errors;
761 + }
725 762
726 - const $recaptcha = jQuery( form ).find( '.frm-g-recaptcha' );
727 - if ( ! $recaptcha.length ) {
763 + const recaptcha = formEl.querySelector( '.frm-g-recaptcha' );
764 + if ( ! recaptcha ) {
728 765 return errors;
729 766 }
730 767
731 - const recaptchaID = $recaptcha.data( 'rid' );
768 + const recaptchaID = recaptcha.dataset.rid;
769 + let response;
732 770
733 771 try {
734 772 response = grecaptcha.getResponse( recaptchaID );
735 773 } catch ( e ) {
736 - if ( jQuery( form ).find( 'input[name="recaptcha_checked"]' ).length ) {
774 + if ( formEl.querySelector( 'input[name="recaptcha_checked"]' ) ) {
737 775 return errors;
738 776 }
739 777 response = '';
740 778 }
@@ -739,11 +777,13 @@
739 777 response = '';
740 778 }
741 779
742 780 if ( response.length === 0 ) {
743 - const fieldContainer = $recaptcha.closest( '.frm_form_field' );
744 - const fieldID = fieldContainer.attr( 'id' ).replace( 'frm_field_', '' ).replace( '_container', '' );
745 - errors[ fieldID ] = '';
781 + const fieldContainer = recaptcha.closest( '.frm_form_field' );
782 + if ( fieldContainer?.id ) {
783 + const fieldID = fieldContainer.id.replace( 'frm_field_', '' ).replace( '_container', '' );
784 + errors[ fieldID ] = '';
785 + }
746 786 }
747 787
748 788 return errors;
749 789 }
@@ -816,16 +856,14 @@
816 856 * @param {string} action
817 857 * @return {void}
818 858 */
819 859 function getFormErrors( object, action ) {
820 - let fieldset, data, success, error, shouldTriggerEvent;
860 + const fieldsets = object.querySelectorAll( '.frm_form_field' );
861 + fieldsets.forEach( field => field.classList.add( 'frm_doing_ajax' ) );
821 862
822 - fieldset = jQuery( object ).find( '.frm_form_field' );
823 - fieldset.addClass( 'frm_doing_ajax' );
863 + const data = `${ jQuery( object ).serialize() }&action=frm_entries_${ action }&nonce=${ frm_js.nonce }`; // eslint-disable-line no-jquery/no-serialize
864 + const shouldTriggerEvent = object.classList.contains( 'frm_trigger_event_on_submit' );
824 865
825 - data = jQuery( object ).serialize() + '&action=frm_entries_' + action + '&nonce=' + frm_js.nonce; // eslint-disable-line camelcase
826 - shouldTriggerEvent = object.classList.contains( 'frm_trigger_event_on_submit' );
827 -
828 866 const doRedirect = response => {
829 867 jQuery( document ).trigger( 'frmBeforeFormRedirect', [ object, response ] );
830 868
831 869 if ( ! response.openInNewTab ) {
@@ -836,17 +874,14 @@
836 874
837 875 // We don't return here because we're opening in a new tab, the old tab will still update.
838 876 const newTab = window.open( response.redirect, '_blank' );
839 877 if ( ! newTab && response.fallbackMsg && response.content ) {
840 - response.content = response.content.trim().replace( /(<\/div><\/div>)$/, ' ' + response.fallbackMsg + '</div></div>' );
878 + response.content = response.content.trim().replace( /(<\/div><\/div>)$/, ` ${ response.fallbackMsg }</div></div>` );
841 879 }
842 880 };
843 881
844 - success = function( response ) {
845 - let defaultResponse, formID, replaceContent, pageOrder, formReturned, contSubmit, delay,
846 - $fieldCont, key, inCollapsedSection, frmTrigger;
847 -
848 - defaultResponse = {
882 + const success = function( response ) {
883 + const defaultResponse = {
849 884 content: '',
850 885 errors: {},
851 886 pass: false
852 887 };
@@ -862,9 +897,11 @@
862 897 response = defaultResponse;
863 898 }
864 899 }
865 900
866 - if ( typeof response.redirect !== 'undefined' ) {
901 + let willRedirect = false;
902 +
903 + if ( response.redirect !== undefined ) {
867 904 if ( shouldTriggerEvent ) {
868 905 triggerCustomEvent( object, 'frmSubmitEvent' );
869 906 return;
870 907 }
@@ -875,8 +912,10 @@
875 912 }, 1000 * response.delay );
876 913 } else {
877 914 doRedirect( response );
878 915 }
916 +
917 + willRedirect = true;
879 918 }
880 919
881 920 if ( 'string' === typeof response.content && response.content !== '' ) {
882 921 // the form or success message was returned
@@ -886,17 +925,18 @@
886 925 return;
887 926 }
888 927
889 928 removeSubmitLoading( jQuery( object ) );
890 - if ( frm_js.offset != -1 ) { // eslint-disable-line camelcase
929 + if ( frm_js.offset != -1 ) {
891 930 frmFrontForm.scrollMsg( jQuery( object ), false );
892 931 }
893 932
894 - formID = jQuery( object ).find( 'input[name="form_id"]' ).val();
933 + const formIdInput = object.querySelector( 'input[name="form_id"]' );
934 + const formID = formIdInput ? formIdInput.value : '';
895 935 response.content = response.content.replace( / frm_pro_form /g, ' frm_pro_form frm_no_hide ' );
896 - replaceContent = jQuery( object ).closest( '.frm_forms' );
936 + const replaceContent = jQuery( object ).closest( '.frm_forms' ); // eslint-disable-line no-jquery/no-closest
897 937 removeAddedScripts( replaceContent, formID );
898 - delay = maybeSlideOut( replaceContent, response.content );
938 + const delay = maybeSlideOut( replaceContent, response.content );
899 939
900 940 setTimeout(
901 941 function() {
902 942 afterFormSubmittedBeforeReplace( object, response );
@@ -905,10 +945,14 @@
905 945
906 946 addUrlParam( response );
907 947
908 948 if ( typeof frmThemeOverride_frmAfterSubmit === 'function' ) { // eslint-disable-line camelcase
909 - pageOrder = jQuery( 'input[name="frm_page_order_' + formID + '"]' ).val();
910 - formReturned = jQuery( response.content ).find( 'input[name="form_id"]' ).val();
949 + const pageOrderInput = document.querySelector( `input[name="frm_page_order_${ formID }"]` );
950 + const pageOrder = pageOrderInput ? pageOrderInput.value : '';
951 + const tempDiv = document.createElement( 'div' );
952 + tempDiv.innerHTML = response.content;
953 + const formReturnedInput = tempDiv.querySelector( 'input[name="form_id"]' );
954 + const formReturned = formReturnedInput ? formReturnedInput.value : '';
911 955 frmThemeOverride_frmAfterSubmit( formReturned, pageOrder, response.content, object );
912 956 }
913 957
914 958 afterFormSubmitted( object, response );
@@ -914,27 +958,28 @@
914 958 afterFormSubmitted( object, response );
915 959 },
916 960 delay
917 961 );
918 - } else if ( Object.keys( response.errors ).length ) {
962 + } else if ( response.errors !== undefined && Object.keys( response.errors ).length ) {
919 963 // errors were returned
920 964 removeSubmitLoading( jQuery( object ), 'enable' );
921 965
922 966 //show errors
923 - contSubmit = true;
967 + let contSubmit = true;
924 968 removeAllErrors();
925 969
926 - $fieldCont = null;
970 + let $fieldCont = null;
927 971
928 - for ( key in response.errors ) {
929 - $fieldCont = jQuery( object ).find( '#frm_field_' + key + '_container' );
972 + for ( const key in response.errors ) {
973 + const fieldContEl = object.querySelector( `#frm_field_${ key }_container` );
974 + $fieldCont = fieldContEl ? jQuery( fieldContEl ) : jQuery();
930 975
931 976 if ( $fieldCont.length ) {
932 - if ( ! $fieldCont.is( ':visible' ) ) {
933 - inCollapsedSection = $fieldCont.closest( '.frm_toggle_container' );
977 + if ( ! $fieldCont.is( ':visible' ) ) { // eslint-disable-line no-jquery/no-is
978 + const inCollapsedSection = $fieldCont.closest( '.frm_toggle_container' ); // eslint-disable-line no-jquery/no-closest, formidable/no-jquery-variable-methods
934 979 if ( inCollapsedSection.length ) {
935 - frmTrigger = inCollapsedSection.prev();
936 - if ( ! frmTrigger.hasClass( 'frm_trigger' ) ) {
980 + let frmTrigger = inCollapsedSection.prev();
981 + if ( ! frmTrigger.hasClass( 'frm_trigger' ) ) { // eslint-disable-line formidable/no-jquery-variable-methods
937 982 // If the frmTrigger object is the section description, check to see if the previous element is the trigger
938 983 frmTrigger = frmTrigger.prev( '.frm_trigger' );
939 984 }
940 985 frmTrigger.trigger( 'click' );
@@ -940,9 +985,9 @@
940 985 frmTrigger.trigger( 'click' );
941 986 }
942 987 }
943 988
944 - if ( $fieldCont.is( ':visible' ) ) {
989 + if ( $fieldCont.is( ':visible' ) ) { // eslint-disable-line no-jquery/no-is
945 990 addFieldError( $fieldCont, key, response.errors );
946 991 contSubmit = false;
947 992 }
948 993 }
@@ -947,11 +992,10 @@
947 992 }
948 993 }
949 994 }
950 995
951 - jQuery( object ).find( '.frm-g-recaptcha, .g-recaptcha, .h-captcha' ).each( function() {
952 - const $recaptcha = jQuery( this ),
953 - recaptchaID = $recaptcha.data( 'rid' );
996 + object.querySelectorAll( '.frm-g-recaptcha, .g-recaptcha, .h-captcha' ).forEach( function( captchaEl ) {
997 + const recaptchaID = captchaEl.dataset.rid;
954 998
955 999 if ( typeof grecaptcha !== 'undefined' && grecaptcha ) {
956 1000 if ( recaptchaID ) {
957 1001 grecaptcha.reset( recaptchaID );
@@ -958,8 +1002,9 @@
958 1002 } else {
959 1003 grecaptcha.reset();
960 1004 }
961 1005 }
1006 +
962 1007 if ( typeof hcaptcha !== 'undefined' && hcaptcha ) {
963 1008 hcaptcha.reset();
964 1009 }
965 1010 } );
@@ -971,9 +1016,9 @@
971 1016 }
972 1017
973 1018 jQuery( document ).trigger( 'frmFormErrors', [ object, response ] );
974 1019
975 - fieldset.removeClass( 'frm_doing_ajax' );
1020 + fieldsets.forEach( field => field.classList.remove( 'frm_doing_ajax' ) );
976 1021 scrollToFirstField( object );
977 1022
978 1023 if ( contSubmit ) {
979 1024 object.submit();
@@ -980,10 +1025,10 @@
980 1025 } else {
981 1026 object.insertAdjacentHTML( 'afterbegin', response.error_message );
982 1027 checkForErrorsAndMaybeSetFocus();
983 1028 }
984 - } else {
985 - // there may have been a plugin conflict, or the form is not set to submit with ajax
1029 + } else if ( ! willRedirect ) { // Avoid double submission if redirecting to a page.
1030 + // There may have been a plugin conflict, or the form is not set to submit with ajax.
986 1031
987 1032 showFileLoading( object );
988 1033
989 1034 object.submit();
@@ -989,10 +1034,12 @@
989 1034 object.submit();
990 1035 }
991 1036 };
992 1037
993 - error = function() {
994 - jQuery( object ).find( 'input[type="submit"], input[type="button"]' ).prop( 'disabled', false );
1038 + const error = function() {
1039 + object.querySelectorAll( 'input[type="submit"], input[type="button"]' ).forEach(
1040 + button => button.disabled = false
1041 + );
995 1042 object.submit();
996 1043 };
997 1044
998 1045 postToAjaxUrl( object, data, success, error );
@@ -998,22 +1045,20 @@
998 1045 postToAjaxUrl( object, data, success, error );
999 1046 }
1000 1047
1001 1048 function postToAjaxUrl( form, data, success, error ) {
1002 - let ajaxUrl, action, ajaxParams;
1049 + let ajaxUrl = frm_js.ajax_url;
1050 + const action = form.getAttribute( 'action' );
1003 1051
1004 - ajaxUrl = frm_js.ajax_url; // eslint-disable-line camelcase
1005 - action = form.getAttribute( 'action' );
1006 -
1007 - if ( 'string' === typeof action && -1 !== action.indexOf( '?action=frm_forms_preview' ) ) {
1052 + if ( 'string' === typeof action && action.includes( '?action=frm_forms_preview' ) ) {
1008 1053 ajaxUrl = action.split( '?action=frm_forms_preview' )[ 0 ];
1009 1054 }
1010 1055
1011 - ajaxParams = {
1056 + const ajaxParams = {
1012 1057 type: 'POST',
1013 1058 url: ajaxUrl,
1014 - data: data,
1015 - success: success
1059 + data,
1060 + success
1016 1061 };
1017 1062
1018 1063 if ( 'function' === typeof error ) {
1019 1064 ajaxParams.error = error;
@@ -1018,14 +1063,16 @@
1018 1063 if ( 'function' === typeof error ) {
1019 1064 ajaxParams.error = error;
1020 1065 }
1021 1066
1022 - jQuery.ajax( ajaxParams );
1067 + jQuery.ajax( ajaxParams ); // eslint-disable-line no-jquery/no-ajax
1023 1068 }
1024 1069
1025 1070 function afterFormSubmitted( object, response ) {
1026 - const formCompleted = jQuery( response.content ).find( '.frm_message' );
1027 - if ( formCompleted.length ) {
1071 + const tempDiv = document.createElement( 'div' );
1072 + tempDiv.innerHTML = response.content;
1073 + const formCompleted = tempDiv.querySelector( '.frm_message' );
1074 + if ( formCompleted ) {
1028 1075 jQuery( document ).trigger( 'frmFormComplete', [ object, response ] );
1029 1076 } else {
1030 1077 jQuery( document ).trigger( 'frmPageChanged', [ object, response ] );
1031 1078 }
@@ -1040,28 +1087,30 @@
1040 1087 * @param {Object} response The response from submitting the form with AJAX.
1041 1088 * @return {void}
1042 1089 */
1043 1090 function afterFormSubmittedBeforeReplace( object, response ) {
1044 - const formCompleted = jQuery( response.content ).find( '.frm_message' );
1045 - if ( formCompleted.length ) {
1091 + const tempDiv = document.createElement( 'div' );
1092 + tempDiv.innerHTML = response.content;
1093 + const formCompleted = tempDiv.querySelector( '.frm_message' );
1094 + if ( formCompleted ) {
1046 1095 triggerCustomEvent( document, 'frmFormCompleteBeforeReplace', { object, response } );
1047 1096 }
1048 1097 }
1049 1098
1050 1099 function removeAddedScripts( formContainer, formID ) {
1051 - const endReplace = jQuery( '.frm_end_ajax_' + formID );
1100 + const endReplace = document.querySelectorAll( `.frm_end_ajax_${ formID }` );
1052 1101 if ( endReplace.length ) {
1053 - formContainer.nextUntil( '.frm_end_ajax_' + formID ).remove();
1054 - endReplace.remove();
1102 + formContainer.nextUntil( `.frm_end_ajax_${ formID }` ).remove();
1103 + endReplace.forEach( el => el.remove() );
1055 1104 }
1056 1105 }
1057 1106
1058 1107 function maybeSlideOut( oldContent, newContent ) {
1059 - let c,
1060 - newClass = 'frm_slideout';
1061 - if ( newContent.indexOf( ' frm_slide' ) !== -1 ) {
1108 + let c;
1109 + let newClass = 'frm_slideout';
1110 + if ( newContent.includes( ' frm_slide' ) ) {
1062 1111 c = oldContent.children();
1063 - if ( newContent.indexOf( ' frm_going_back' ) !== -1 ) {
1112 + if ( newContent.includes( ' frm_going_back' ) ) {
1064 1113 newClass += ' frm_going_back';
1065 1114 }
1066 1115 c.removeClass( 'frm_going_back' );
1067 1116 c.addClass( newClass );
@@ -1071,25 +1120,23 @@
1071 1120 }
1072 1121
1073 1122 function addUrlParam( response ) {
1074 1123 let url;
1075 - if ( history.pushState && typeof response.page !== 'undefined' ) {
1124 + if ( history.pushState && response.page !== undefined ) {
1076 1125 url = addQueryVar( 'frm_page', response.page );
1077 - window.history.pushState( { html: response.html }, '', '?' + url );
1126 + window.history.pushState( { html: response.html }, '', `?${ url }` );
1078 1127 }
1079 1128 }
1080 1129
1081 1130 function addQueryVar( key, value ) {
1082 - let kvp, i, x;
1083 -
1084 1131 key = encodeURI( key );
1085 1132 value = encodeURI( value );
1086 1133
1087 - kvp = document.location.search.substr( 1 ).split( '&' );
1134 + const kvp = document.location.search.substr( 1 ).split( '&' );
1088 1135
1089 - i = kvp.length;
1136 + let i = kvp.length;
1090 1137 while ( i-- ) {
1091 - x = kvp[ i ].split( '=' );
1138 + const x = kvp[ i ].split( '=' );
1092 1139
1093 1140 if ( x[ 0 ] == key ) {
1094 1141 x[ 1 ] = value;
1095 1142 kvp[ i ] = x.join( '=' );
@@ -1104,49 +1151,59 @@
1104 1151 return kvp.join( '&' );
1105 1152 }
1106 1153
1107 1154 function addFieldError( $fieldCont, key, jsErrors ) {
1108 - let input, id, describedBy, roleString;
1109 - if ( $fieldCont.length && $fieldCont.is( ':visible' ) ) {
1110 - $fieldCont.addClass( 'frm_blank_field' );
1111 - input = $fieldCont.find( 'input, select, textarea' );
1112 - id = getErrorElementId( key, input.get( 0 ) );
1155 + const container = $fieldCont instanceof jQuery ? $fieldCont.get( 0 ) : $fieldCont;
1113 1156
1114 - describedBy = input.attr( 'aria-describedby' );
1157 + if ( ! container || container.offsetParent === null ) {
1158 + return;
1159 + }
1115 1160
1116 - if ( typeof frmThemeOverride_frmPlaceError === 'function' ) { // eslint-disable-line camelcase
1117 - frmThemeOverride_frmPlaceError( key, jsErrors );
1161 + container.classList.add( 'frm_blank_field' );
1162 + const inputs = container.querySelectorAll( 'input, select, textarea' );
1163 + const id = getErrorElementId( key, inputs[ 0 ] );
1164 +
1165 + let describedBy;
1166 +
1167 + if ( typeof frmThemeOverride_frmPlaceError === 'function' ) { // eslint-disable-line camelcase
1168 + frmThemeOverride_frmPlaceError( key, jsErrors );
1169 + } else {
1170 + let errorHtml;
1171 + if ( jsErrors[ key ].includes( '<div' ) ) {
1172 + errorHtml = jsErrors[ key ];
1118 1173 } else {
1119 - if ( -1 !== jsErrors[ key ].indexOf( '<div' ) ) {
1120 - $fieldCont.append(
1121 - jsErrors[ key ]
1122 - );
1123 - } else {
1124 - roleString = frm_js.include_alert_role ? 'role="alert"' : ''; // eslint-disable-line camelcase
1125 - $fieldCont.append( '<div class="frm_error" ' + roleString + ' id="' + id + '">' + jsErrors[ key ] + '</div>' );
1126 - }
1127 -
1128 - if ( typeof describedBy === 'undefined' ) {
1174 + const roleString = frm_js.include_alert_role ? 'role="alert"' : '';
1175 + errorHtml = `<div class="frm_error" ${ roleString } id="${ id }">${ jsErrors[ key ] }</div>`;
1176 + }
1177 + container.insertAdjacentHTML( 'beforeend', errorHtml );
1178 + inputs.forEach( input => {
1179 + describedBy = input.getAttribute( 'aria-describedby' );
1180 + if ( ! describedBy ) {
1129 1181 describedBy = id;
1130 - } else if ( describedBy.indexOf( id ) === -1 && describedBy.indexOf( 'frm_error_field_' ) === -1 ) {
1131 - if ( input.data( 'error-first' ) === 0 ) {
1132 - describedBy = describedBy + ' ' + id;
1182 + } else if ( ! describedBy.includes( id ) && ! describedBy.includes( 'frm_error_field_' ) ) {
1183 + const { errorFirst } = input.dataset;
1184 + if ( errorFirst === '0' ) {
1185 + describedBy = `${ describedBy } ${ id }`;
1133 1186 } else {
1134 - describedBy = id + ' ' + describedBy;
1187 + describedBy = `${ id } ${ describedBy }`;
1135 1188 }
1136 1189 }
1190 + input.setAttribute( 'aria-describedby', describedBy );
1191 + } );
1192 + }
1137 1193
1138 - input.attr( 'aria-describedby', describedBy );
1139 - }
1140 -
1141 - if ( [ 'radio', 'checkbox' ].includes( input.attr( 'type' ) ) ) {
1142 - input.closest( '[role="radiogroup"], [role="group"]' ).attr( 'aria-invalid', true );
1194 + inputs.forEach( input => {
1195 + if ( [ 'radio', 'checkbox' ].includes( input.type ) ) {
1196 + const group = input.closest( '[role="radiogroup"], [role="group"]' );
1197 + if ( group ) {
1198 + group.setAttribute( 'aria-invalid', 'true' );
1199 + }
1143 1200 } else {
1144 - input.attr( 'aria-invalid', true );
1201 + input.setAttribute( 'aria-invalid', 'true' );
1145 1202 }
1203 + } );
1146 1204
1147 - jQuery( document ).trigger( 'frmAddFieldError', [ $fieldCont, key, jsErrors ] );
1148 - }
1205 + jQuery( document ).trigger( 'frmAddFieldError', [ jQuery( container ), key, jsErrors ] );
1149 1206 }
1150 1207
1151 1208 /**
1152 1209 * Get the ID to use for an error element added when submitting with AJAX.
@@ -1157,11 +1214,11 @@
1157 1214 */
1158 1215 function getErrorElementId( key, input ) {
1159 1216 if ( isNaN( key ) || ! input || ! input.id ) {
1160 1217 // If key isn't a number, assume it's already in the right format.
1161 - return 'frm_error_field_' + key;
1218 + return `frm_error_field_${ key }`;
1162 1219 }
1163 - return 'frm_error_' + input.id;
1220 + return `frm_error_${ input.id }`;
1164 1221 }
1165 1222
1166 1223 /**
1167 1224 * Removes errors before validating with JS.
@@ -1166,41 +1223,72 @@
1166 1223 /**
1167 1224 * Removes errors before validating with JS.
1168 1225 * This prevents issues with stale errors that has since been fixed.
1169 1226 *
1170 - * @param {Object} $fieldCont jQuery object.
1227 + * @param {HTMLElement|jQuery} fieldCont Field container element.
1171 1228 * @return {void}
1172 1229 */
1173 - function removeFieldError( $fieldCont ) {
1174 - const errorMessage = $fieldCont.find( '.frm_error' );
1175 - const errorId = errorMessage.attr( 'id' );
1176 - const input = $fieldCont.find( 'input, select, textarea' );
1177 - let describedBy = input.attr( 'aria-describedby' );
1230 + function removeFieldError( fieldCont ) {
1231 + const container = fieldCont instanceof jQuery ? fieldCont.get( 0 ) : fieldCont;
1232 + if ( ! container ) {
1233 + return;
1234 + }
1178 1235
1179 - const fieldContainer = $fieldCont.get( 0 );
1180 - if ( fieldContainer && fieldContainer.classList ) {
1181 - fieldContainer.classList.remove( 'frm_blank_field', 'has-error' );
1236 + const errorMessage = container.querySelector( '.frm_error' );
1237 + const input = container.querySelector( 'input, select, textarea' );
1238 +
1239 + container.classList.remove( 'frm_blank_field', 'has-error' );
1240 +
1241 + if ( input ) {
1242 + if ( 'true' === input.getAttribute( 'aria-invalid' ) ) {
1243 + input.setAttribute( 'aria-invalid', 'false' );
1244 + } else if ( [ 'radio', 'checkbox' ].includes( input.type ) ) {
1245 + const group = input.closest( '[role="radiogroup"], [role="group"]' );
1246 + if ( group ) {
1247 + group.setAttribute( 'aria-invalid', 'false' );
1248 + }
1249 + }
1182 1250 }
1183 1251
1184 - if ( 'true' === input.attr( 'aria-invalid' ) ) {
1185 - input.attr( 'aria-invalid', false );
1186 - } else if ( [ 'radio', 'checkbox' ].includes( input.attr( 'type' ) ) ) {
1187 - input.closest( '[role="radiogroup"], [role="group"]' ).attr( 'aria-invalid', false );
1252 + if ( errorMessage ) {
1253 + removeElementFromInputDescribedBy( errorMessage );
1254 + errorMessage.remove();
1188 1255 }
1256 + }
1189 1257
1190 - errorMessage.remove();
1191 - input.removeAttr( 'aria-describedby' );
1258 + /**
1259 + * Updates the aria-describedby attribute, removing the target element ID.
1260 + *
1261 + * @since 6.32
1262 + *
1263 + * @param {HTMLElement} el The target element that is removed from the aria-describedby data.
1264 + * @return {void}
1265 + */
1266 + function removeElementFromInputDescribedBy( el ) {
1267 + document.querySelectorAll( `[aria-describedby*="${ el.id }"]` ).forEach( input => {
1268 + let ariaDescribedBy = input.getAttribute( 'aria-describedby' ).split( ' ' );
1269 + ariaDescribedBy = ariaDescribedBy.filter( value => {
1270 + const trimmedValue = value.trim();
1271 + return trimmedValue && trimmedValue !== el.id;
1272 + } );
1192 1273
1193 - if ( typeof describedBy !== 'undefined' ) {
1194 - describedBy = describedBy.replace( errorId, '' );
1195 - input.attr( 'aria-describedby', describedBy );
1196 - }
1274 + if ( ariaDescribedBy.length ) {
1275 + input.setAttribute( 'aria-describedby', ariaDescribedBy.join( ' ' ) );
1276 + return;
1277 + }
1278 + input.removeAttribute( 'aria-describedby' );
1279 + } );
1197 1280 }
1198 1281
1199 1282 function removeAllErrors() {
1200 - jQuery( '.form-field' ).removeClass( 'frm_blank_field has-error' );
1201 - jQuery( '.form-field .frm_error' ).replaceWith( '' );
1202 - jQuery( '.frm_error_style' ).remove();
1283 + document.querySelectorAll( '.form-field' ).forEach( field => {
1284 + field.classList.remove( 'frm_blank_field', 'has-error' );
1285 + } );
1286 + document.querySelectorAll( '.form-field .frm_error' ).forEach( el => {
1287 + removeElementFromInputDescribedBy( el );
1288 + el.remove();
1289 + } );
1290 + document.querySelectorAll( '.frm_error_style' ).forEach( error => error.remove() );
1203 1291 }
1204 1292
1205 1293 /**
1206 1294 * @param {HTMLElement|Object} object Form object.
@@ -1223,9 +1311,9 @@
1223 1311 disableSaveDraft( $object );
1224 1312 }
1225 1313
1226 1314 function showLoadingIndicator( $object ) {
1227 - if ( ! $object.hasClass( 'frm_loading_form' ) && ! $object.hasClass( 'frm_loading_prev' ) ) {
1315 + if ( ! $object.hasClass( 'frm_loading_form' ) && ! $object.hasClass( 'frm_loading_prev' ) ) { // eslint-disable-line no-jquery/no-class, formidable/no-jquery-variable-methods
1228 1316 addLoadingClass( $object );
1229 1317 $object.trigger( 'frmStartFormLoading' );
1230 1318 }
1231 1319 }
@@ -1232,44 +1320,43 @@
1232 1320
1233 1321 function addLoadingClass( $object ) {
1234 1322 const loadingClass = isGoingToPrevPage( $object ) ? 'frm_loading_prev' : 'frm_loading_form';
1235 1323
1236 - $object.addClass( loadingClass );
1324 + $object.addClass( loadingClass ); // eslint-disable-line no-jquery/no-class, formidable/no-jquery-variable-methods
1237 1325 }
1238 1326
1239 1327 function isGoingToPrevPage( $object ) {
1240 - return ( typeof frmProForm !== 'undefined' && frmProForm.goingToPreviousPage( $object ) );
1328 + return typeof frmProForm !== 'undefined' && frmProForm.goingToPreviousPage( $object );
1241 1329 }
1242 1330
1243 1331 function removeSubmitLoading( _, enable, processesRunning ) {
1244 - let loadingForm;
1245 -
1246 1332 if ( processesRunning > 0 ) {
1247 1333 return;
1248 1334 }
1249 1335
1250 - loadingForm = jQuery( '.frm_loading_form' );
1251 - loadingForm.removeClass( 'frm_loading_form' );
1252 - loadingForm.removeClass( 'frm_loading_prev' );
1336 + document.querySelectorAll( '.frm_loading_form' ).forEach( function( form ) {
1337 + form.classList.remove( 'frm_loading_form', 'frm_loading_prev' );
1338 + jQuery( form ).trigger( 'frmEndFormLoading' );
1253 1339
1254 - loadingForm.trigger( 'frmEndFormLoading' );
1340 + if ( enable === 'enable' ) {
1341 + enableSubmitButton( form );
1342 + enableSaveDraft( form );
1343 + }
1344 + } );
1345 + }
1255 1346
1256 - if ( enable === 'enable' ) {
1257 - enableSubmitButton( loadingForm );
1258 - enableSaveDraft( loadingForm );
1347 + function showFileLoading( object ) {
1348 + const loading = document.getElementById( 'frm_loading' );
1349 + if ( ! loading ) {
1350 + return;
1259 1351 }
1260 - }
1261 1352
1262 - function showFileLoading( object ) {
1263 - let fileval,
1264 - loading = document.getElementById( 'frm_loading' );
1265 - if ( loading !== null ) {
1266 - fileval = jQuery( object ).find( 'input[type=file]' ).val();
1267 - if ( typeof fileval !== 'undefined' && fileval !== '' ) {
1268 - setTimeout( function() {
1269 - jQuery( loading ).fadeIn( 'slow' );
1270 - }, 2000 );
1271 - }
1353 + const fileInput = object.querySelector( 'input[type=file]' );
1354 + const fileval = fileInput ? fileInput.value : '';
1355 + if ( fileval !== '' ) {
1356 + setTimeout( function() {
1357 + jQuery( loading ).fadeIn( 'slow' ); // eslint-disable-line no-jquery/no-fade
1358 + }, 2000 );
1272 1359 }
1273 1360 }
1274 1361
1275 1362 /**********************************************
@@ -1277,9 +1364,9 @@
1277 1364 *********************************************/
1278 1365
1279 1366 function confirmClick() {
1280 1367 /*jshint validthis:true */
1281 - const message = jQuery( this ).data( 'frmconfirm' );
1368 + const message = this.dataset.frmconfirm;
1282 1369 return confirm( message );
1283 1370 }
1284 1371
1285 1372 /**
@@ -1287,11 +1374,12 @@
1287 1374 * If this is a match, the User is autofilling the input on a Webkit browser.
1288 1375 * We want to delete the Honeypot field, otherwise it will get triggered as spam on autocomplete.
1289 1376 */
1290 1377 function onHoneypotFieldChange() {
1291 - const css = jQuery( this ).css( 'box-shadow' );
1292 - if ( css.match( /inset/ ) ) {
1293 - this.parentNode.removeChild( this );
1378 + /*jshint validthis:true */
1379 + const css = window.getComputedStyle( this ).boxShadow;
1380 + if ( css?.match( /inset/ ) ) {
1381 + this.remove();
1294 1382 }
1295 1383 }
1296 1384
1297 1385 /**
@@ -1342,23 +1430,22 @@
1342 1430 return false;
1343 1431 }
1344 1432
1345 1433 function checkForErrorsAndMaybeSetFocus() {
1346 - let errors, element, timeoutCallback;
1347 -
1348 - if ( ! frm_js.focus_first_error ) { // eslint-disable-line camelcase
1434 + if ( ! frm_js.focus_first_error ) {
1349 1435 return;
1350 1436 }
1351 1437
1352 - errors = document.querySelectorAll( '.frm_form_field .frm_error' );
1438 + const errors = document.querySelectorAll( '.frm_form_field .frm_error' );
1353 1439 if ( ! errors.length ) {
1354 1440 return;
1355 1441 }
1356 1442
1357 - element = errors[ 0 ];
1443 + let element = errors[ 0 ];
1444 + let timeoutCallback;
1358 1445 do {
1359 1446 element = element.previousSibling;
1360 - if ( -1 !== [ 'input', 'select', 'textarea' ].indexOf( element.nodeName.toLowerCase() ) ) {
1447 + if ( [ 'input', 'select', 'textarea' ].includes( element.nodeName.toLowerCase() ) ) {
1361 1448 focusInput( element );
1362 1449 break;
1363 1450 }
1364 1451
@@ -1365,9 +1452,9 @@
1365 1452 if ( maybeFocusOnComboSubField( element ) ) {
1366 1453 break;
1367 1454 }
1368 1455
1369 - if ( 'undefined' !== typeof element.classList ) {
1456 + if ( element.classList !== undefined ) {
1370 1457 if ( element.classList.contains( 'html-active' ) ) {
1371 1458 timeoutCallback = function() {
1372 1459 const textarea = element.querySelector( 'textarea' );
1373 1460 if ( null !== textarea ) {
@@ -1420,9 +1507,9 @@
1420 1507 * @param {Function} handler Handler.
1421 1508 * @param {boolean | Object} options Options to be added to `addEventListener()` method. Default is `false`.
1422 1509 */
1423 1510 function documentOn( event, selector, handler, options ) {
1424 - if ( 'undefined' === typeof options ) {
1511 + if ( options === undefined ) {
1425 1512 options = false;
1426 1513 }
1427 1514
1428 1515 document.addEventListener( event, function( e ) {
@@ -1429,9 +1516,9 @@
1429 1516 let target;
1430 1517
1431 1518 // loop parent nodes from the target to the delegation node.
1432 1519 for ( target = e.target; target && target != this; target = target.parentNode ) {
1433 - if ( target && target.matches && target.matches( selector ) ) {
1520 + if ( target.matches && target.matches( selector ) ) {
1434 1521 handler.call( target, e );
1435 1522 break;
1436 1523 }
1437 1524 }
@@ -1438,27 +1525,23 @@
1438 1525 }, options );
1439 1526 }
1440 1527
1441 1528 function initFloatingLabels() {
1442 - let checkFloatLabel, checkDropdownLabel, runOnLoad, selector, floatClass;
1529 + const selector = '.frm-show-form .frm_inside_container input, .frm-show-form .frm_inside_container select, .frm-show-form .frm_inside_container textarea';
1530 + const floatClass = 'frm_label_float_top';
1443 1531
1444 - selector = '.frm-show-form .frm_inside_container input, .frm-show-form .frm_inside_container select, .frm-show-form .frm_inside_container textarea';
1445 - floatClass = 'frm_label_float_top';
1446 -
1447 - checkFloatLabel = function( input ) {
1448 - let container, shouldFloatTop, firstOpt;
1449 -
1450 - container = input.closest( '.frm_inside_container' );
1532 + const checkFloatLabel = function( input ) {
1533 + const container = input.closest( '.frm_inside_container' );
1451 1534 if ( ! container ) {
1452 1535 return;
1453 1536 }
1454 1537
1455 - shouldFloatTop = input.value || document.activeElement === input;
1538 + const shouldFloatTop = input.value || document.activeElement === input;
1456 1539
1457 1540 container.classList.toggle( floatClass, shouldFloatTop );
1458 1541
1459 1542 if ( 'SELECT' === input.tagName ) {
1460 - firstOpt = input.querySelector( 'option:first-child' );
1543 + const firstOpt = input.querySelector( 'option:first-child' );
1461 1544
1462 1545 if ( shouldFloatTop ) {
1463 1546 if ( firstOpt.hasAttribute( 'data-label' ) ) {
1464 1547 firstOpt.textContent = firstOpt.getAttribute( 'data-label' );
@@ -1470,10 +1553,10 @@
1470 1553 }
1471 1554 }
1472 1555 };
1473 1556
1474 - checkDropdownLabel = function() {
1475 - document.querySelectorAll( '.frm-show-form .frm_inside_container:not(.' + floatClass + ') select' ).forEach( function( input ) {
1557 + const checkDropdownLabel = function() {
1558 + document.querySelectorAll( `.frm-show-form .frm_inside_container:not(.${ floatClass }) select` ).forEach( function( input ) {
1476 1559 const firstOpt = input.querySelector( 'option:first-child' );
1477 1560
1478 1561 if ( firstOpt.textContent ) {
1479 1562 firstOpt.setAttribute( 'data-label', firstOpt.textContent );
@@ -1492,14 +1575,10 @@
1492 1575 true
1493 1576 );
1494 1577 } );
1495 1578
1496 - jQuery( document ).on( 'change', selector, function( event ) {
1497 - checkFloatLabel( event.target );
1498 - } );
1499 -
1500 - runOnLoad = function( firstLoad ) {
1501 - if ( firstLoad && document.activeElement && -1 !== [ 'INPUT', 'SELECT', 'TEXTAREA' ].indexOf( document.activeElement.tagName ) ) {
1579 + const runOnLoad = function( firstLoad ) {
1580 + if ( firstLoad && document.activeElement && [ 'INPUT', 'SELECT', 'TEXTAREA' ].includes( document.activeElement.tagName ) ) {
1502 1581 checkFloatLabel( document.activeElement );
1503 1582 } else if ( firstLoad ) {
1504 1583 document.querySelectorAll( '.frm_inside_container' ).forEach(
1505 1584 function( container ) {
@@ -1511,8 +1590,9 @@
1511 1590 );
1512 1591 }
1513 1592
1514 1593 checkDropdownLabel();
1594 + calcProductsTotal();
1515 1595 };
1516 1596
1517 1597 runOnLoad( true );
1518 1598
@@ -1545,10 +1625,10 @@
1545 1625 return true;
1546 1626 }
1547 1627
1548 1628 function maybeClearCustomValidityMessage( event, field ) {
1549 - let key,
1550 - isInvalid = false;
1629 + let key;
1630 + let isInvalid = false;
1551 1631
1552 1632 if ( ! shouldUpdateValidityMessage( field ) ) {
1553 1633 return;
1554 1634 }
@@ -1568,33 +1648,29 @@
1568 1648 }
1569 1649 }
1570 1650
1571 1651 function maybeShowNewTabFallbackMessage() {
1572 - let messageEl;
1573 -
1574 1652 if ( ! window.frmShowNewTabFallback ) {
1575 1653 return;
1576 1654 }
1577 1655
1578 - messageEl = document.querySelector( '#frm_form_' + frmShowNewTabFallback.formId + '_container .frm_message' );
1656 + const messageEl = document.querySelector( `#frm_form_${ frmShowNewTabFallback.formId }_container .frm_message` );
1579 1657 if ( ! messageEl ) {
1580 1658 return;
1581 1659 }
1582 1660
1583 - messageEl.insertAdjacentHTML( 'beforeend', ' ' + frmShowNewTabFallback.message );
1661 + messageEl.insertAdjacentHTML( 'beforeend', ` ${ frmShowNewTabFallback.message }` );
1584 1662 }
1585 1663
1586 1664 function setCustomValidityMessage() {
1587 - let forms, length, index;
1665 + const forms = document.getElementsByClassName( 'frm-show-form' );
1666 + const { length } = forms;
1588 1667
1589 - forms = document.getElementsByClassName( 'frm-show-form' );
1590 - length = forms.length;
1591 -
1592 - for ( index = 0; index < length; ++index ) {
1668 + for ( let index = 0; index < length; ++index ) {
1593 1669 forms[ index ].addEventListener(
1594 1670 'invalid',
1595 1671 function( event ) {
1596 - const target = event.target;
1672 + const { target } = event;
1597 1673
1598 1674 if ( shouldUpdateValidityMessage( target ) ) {
1599 1675 target.setCustomValidity( target.dataset.invmsg );
1600 1676 }
@@ -1608,9 +1684,9 @@
1608 1684 window.addEventListener( 'pageshow', function( event ) {
1609 1685 if ( event.persisted ) {
1610 1686 document.querySelectorAll( '.frm_loading_form' ).forEach(
1611 1687 function( form ) {
1612 - enableSubmitButton( jQuery( form ) );
1688 + enableSubmitButton( form );
1613 1689 }
1614 1690 );
1615 1691 removeSubmitLoading();
1616 1692 }
@@ -1636,9 +1712,9 @@
1636 1712 const uniqueKey = Array.from( window.crypto.getRandomValues( new Uint8Array( 8 ) ) )
1637 1713 .map( b => b.toString( 16 ).padStart( 2, '0' ) )
1638 1714 .join( '' );
1639 1715 const timestamp = Date.now().toString( 16 );
1640 - return uniqueKey + '-' + timestamp;
1716 + return `${ uniqueKey }-${ timestamp }`;
1641 1717 }
1642 1718
1643 1719 /**
1644 1720 * Animates the scroll position of the document.
@@ -1655,9 +1731,8 @@
1655 1731 document.documentElement.scrollTop = end;
1656 1732 return;
1657 1733 }
1658 1734
1659 - /* eslint-disable compat/compat */
1660 1735 const startTime = performance.now();
1661 1736 const step = currentTime => {
1662 1737 const progress = Math.min( ( currentTime - startTime ) / duration, 1 );
1663 1738 document.documentElement.scrollTop = start + ( ( end - start ) * progress );
@@ -1665,9 +1740,8 @@
1665 1740 requestAnimationFrame( step );
1666 1741 }
1667 1742 };
1668 1743 requestAnimationFrame( step );
1669 - /* eslint-enable compat/compat */
1670 1744 }
1671 1745
1672 1746 /**
1673 1747 * Make sure that the captcha label for a reCAPTCHA or Turnstile field matches the response input ID.
@@ -1692,19 +1766,436 @@
1692 1766 label.htmlFor = captchaResponse.id;
1693 1767 }
1694 1768 }
1695 1769
1770 + /**
1771 + * Check to make sure the quantity field value is within the min and max values.
1772 + *
1773 + * @param {HTMLElement} input
1774 + * @return {number} The quantity value.
1775 + */
1776 + function checkQuantityFieldMinMax( input ) {
1777 + if ( '' === input.value ) {
1778 + // Leave the value if it is empty.
1779 + return 0;
1780 + }
1781 +
1782 + const val = parseFloat( input.value ? input.value.trim() : 0 );
1783 + if ( isNaN( val ) ) {
1784 + return 0;
1785 + }
1786 +
1787 + let max = input.hasAttribute( 'max' ) ? parseFloat( input.getAttribute( 'max' ) ) : 0;
1788 + let min = input.hasAttribute( 'min' ) ? parseFloat( input.getAttribute( 'min' ) ) : 0;
1789 +
1790 + max = isNaN( max ) ? 0 : max;
1791 + min = isNaN( min ) ? 0 : Math.max( 0, min );
1792 +
1793 + if ( val < min ) {
1794 + input.value = min;
1795 + return min;
1796 + }
1797 +
1798 + if ( 0 !== max && val > max ) {
1799 + input.value = max;
1800 + return max;
1801 + }
1802 +
1803 + return val;
1804 + }
1805 +
1806 + function triggerChange( input, fieldKey ) {
1807 + if ( fieldKey === undefined ) {
1808 + fieldKey = 'dependent';
1809 + }
1810 +
1811 + jQuery( input ).trigger( { type: 'change', selfTriggered: true, frmTriggered: fieldKey } );
1812 + }
1813 +
1814 + /**
1815 + * Calculates the total price.
1816 + *
1817 + * @param {Event|undefined} e The event object.
1818 + * @return {void}
1819 + */
1820 + function calcProductsTotal( e ) {
1821 + if ( 'object' === typeof frmProForm ) {
1822 + // Pro is installed, use the Pro JS.
1823 + return;
1824 + }
1825 +
1826 + if ( typeof __FRMCURR === 'undefined' ) {
1827 + return;
1828 + }
1829 +
1830 + const totalFields = document.querySelectorAll( '[data-frmtotal]' );
1831 + if ( ! totalFields.length ) {
1832 + return;
1833 + }
1834 +
1835 + const formTotals = [];
1836 +
1837 + totalFields.forEach( totalField => {
1838 + let total = 0;
1839 + const form = totalField.closest( 'form' );
1840 +
1841 + if ( ! form ) {
1842 + return;
1843 + }
1844 +
1845 + const formId = form.querySelector( 'input[name="form_id"]' ).value;
1846 + const currency = getCurrency( formId );
1847 +
1848 + if ( undefined !== formTotals[ formId ] ) {
1849 + total = formTotals[ formId ];
1850 + } else {
1851 + form.querySelectorAll( 'input[data-frmprice],select:has([data-frmprice])' ).forEach( function( input ) {
1852 + let quantity = 0;
1853 + let price = 0;
1854 + const isSingle = 'hidden' === input.type;
1855 +
1856 + if ( input.tagName === 'SELECT' ) {
1857 + if ( input.selectedIndex !== -1 ) {
1858 + price = input.options[ input.selectedIndex ].getAttribute( 'data-frmprice' );
1859 + }
1860 + } else {
1861 + if ( ! isSingle && ! input.matches( ':checked' ) ) {
1862 + return;
1863 + }
1864 + price = input.getAttribute( 'data-frmprice' );
1865 + }
1866 +
1867 + if ( ! price ) {
1868 + price = 0;
1869 + } else {
1870 + price = preparePrice( price, currency );
1871 + quantity = getQuantity( input );
1872 + price = parseFloat( quantity ) * parseFloat( price );
1873 + }
1874 +
1875 + if ( 'true' === input.getAttribute( 'data-frmdiscount' ) ) {
1876 + price = price * -1;
1877 + }
1878 +
1879 + total += price;
1880 + } );
1881 +
1882 + formTotals[ formId ] = total;
1883 + }
1884 +
1885 + total = isNaN( total ) ? 0 : total;
1886 +
1887 + // Set a decimal separator for currency if no default for it
1888 + currency.decimal_separator = currency.decimal_separator.trim(); // first remove unnecessary space(s)
1889 + if ( ! currency.decimal_separator.length ) {
1890 + currency.decimal_separator = '.';
1891 + }
1892 +
1893 + totalField.value = roundTotal( total, currency );
1894 + total = normalizeTotal( total, currency );
1895 +
1896 + // because of e.g. fields that might be using this field for calculations
1897 + triggerChange( totalField );
1898 +
1899 + total = formatCurrency( total, currency );
1900 + const formatted = totalField.previousElementSibling;
1901 + if ( formatted?.matches( '.frm_total_formatted' ) ) {
1902 + // Use innerHTML so that currency symbols like Euros can render and not their encoded string value.
1903 + formatted.innerHTML = total;
1904 + return;
1905 + }
1906 +
1907 + const formattedEls = totalField.closest( '.frm_form_field' ).querySelectorAll( '.frm_total_formatted' );
1908 + formattedEls.forEach( formattedEl => {
1909 + // Use innerHTML so that currency symbols like Euros can render and not their encoded string value.
1910 + formattedEl.innerHTML = total;
1911 + } );
1912 + } );
1913 + }
1914 +
1915 + /**
1916 + * Round total and maybe add trailing zeros so formatCurrency has a proper format to work with.
1917 + *
1918 + * @param {number} total The total amount to normalize.
1919 + * @param {Object} currency The currency object containing decimal information.
1920 + * @return {string} The normalized total amount.
1921 + */
1922 + function normalizeTotal( total, currency ) {
1923 + const isLargeTotal = total > Number.MAX_SAFE_INTEGER;
1924 +
1925 + total = roundTotal( total, currency );
1926 +
1927 + return maybeAddTrailingZeroToPrice( total, currency, isLargeTotal );
1928 + }
1929 +
1930 + function roundTotal( total, currency ) {
1931 + const isLargeTotal = total > Number.MAX_SAFE_INTEGER;
1932 +
1933 + if ( ! isLargeTotal ) {
1934 + const { decimals } = currency;
1935 + total = decimals > 0 ? round10( total, decimals ) : Math.ceil( total );
1936 + }
1937 +
1938 + return total;
1939 + }
1940 +
1941 + function round10( value, decimals ) {
1942 + return Number( `${ Math.round( `${ value }e${ decimals }` ) }e-${ decimals }` );
1943 + }
1944 +
1945 + /**
1946 + * Format a numeric value according to the specified currency format settings.
1947 + *
1948 + * @param {string} total The numeric value to format.
1949 + * @param {Object} currency The currency formatting configuration.
1950 + * @return {string} The formatted currency string.
1951 + */
1952 + function formatCurrency( total, currency ) {
1953 + total = maybeAddTrailingZeroToPrice( total, currency );
1954 + if ( total.length && ( total[ total.length - 1 ] === '.' || total[ total.length - 1 ] === currency.decimal_separator ) ) {
1955 + total = total.substr( 0, total.length - 1 );
1956 + }
1957 +
1958 + total = maybeRemoveTrailingZerosFromPrice( total, currency );
1959 + total = addThousands( total, currency );
1960 +
1961 + const leftSymbol = currency.symbol_left ? ( currency.symbol_left + currency.symbol_padding ) : '';
1962 + const rightSymbol = currency.symbol_right ? ( currency.symbol_padding + currency.symbol_right ) : '';
1963 +
1964 + return `${ leftSymbol }${ total }${ rightSymbol }`;
1965 + }
1966 +
1967 + /**
1968 + * Gets currency from form id.
1969 + *
1970 + * @param {number} formId Form ID.
1971 + * @return {Object} Currency object.
1972 + */
1973 + function getCurrency( formId ) {
1974 + if ( undefined !== window.__FRMCURR && undefined !== window.__FRMCURR[ formId ] ) {
1975 + return window.__FRMCURR[ formId ];
1976 + }
1977 +
1978 + return {
1979 + symbol_left: '$',
1980 + symbol_right: '',
1981 + symbol_padding: '',
1982 + thousand_separator: ',',
1983 + decimal_separator: '.',
1984 + decimals: 2,
1985 + };
1986 + }
1987 +
1988 + /**
1989 + * Gets quantity.
1990 + *
1991 + * @param {HTMLElement} field The field element.
1992 + * @return {number} The quantity.
1993 + */
1994 + function getQuantity( field ) {
1995 + const fieldID = frmFrontForm.getFieldId( field, false );
1996 + if ( ! fieldID ) {
1997 + return 0;
1998 + }
1999 +
2000 + const quantityField = getQuantityField( field, fieldID );
2001 + if ( ! quantityField ) {
2002 + // If there is no quantity field, assume 1.
2003 + return 1;
2004 + }
2005 +
2006 + return checkQuantityFieldMinMax( quantityField );
2007 + }
2008 +
2009 + /**
2010 + * Gets quantity field.
2011 + *
2012 + * @param {HTMLElement} element The element.
2013 + * @param {number} fieldID The field ID.
2014 + * @return {HTMLElement|null} The quantity field.
2015 + */
2016 + function getQuantityField( element, fieldID ) {
2017 + const quantityFields = element.closest( 'form' ).querySelectorAll( '[data-frmproduct]' );
2018 + if ( ! quantityFields.length ) {
2019 + return null;
2020 + }
2021 +
2022 + fieldID = fieldID.toString();
2023 +
2024 + return Array.from( quantityFields ).find( element => {
2025 + let ids;
2026 +
2027 + ids = JSON.parse( element.getAttribute( 'data-frmproduct' ).trim() );
2028 + if ( '' === ids ) {
2029 + return false;
2030 + }
2031 +
2032 + // Convert to array if necessary because of existing fields that are already using single product fields.
2033 + ids = 'string' === typeof ids ? [ ids ] : ids;
2034 + return ids.includes( fieldID );
2035 + } );
2036 + }
2037 +
2038 + /**
2039 + * Prepare a price for calculation.
2040 + *
2041 + * @param {number|string} price The price to prepare.
2042 + * @param {Object} currency The currency object containing decimal information.
2043 + * @return {string} The prepared price.
2044 + */
2045 + function preparePrice( price, currency ) {
2046 + if ( ! price ) {
2047 + return 0;
2048 + }
2049 + price = `${ price }`; // convert to string just to be sure
2050 +
2051 + const regex = getRegexForPrice( currency );
2052 +
2053 + const matches = price.match( regex );
2054 + if ( null === matches ) {
2055 + return 0;
2056 + }
2057 +
2058 + price = matches.length ? matches[ matches.length - 1 ] : 0;
2059 + price = price.trim();
2060 +
2061 + // Fix issues with parsing Fr.15.00. The regex catches .15.00.
2062 + // This checks for the leading decimal and removes it.
2063 + if ( currency.decimal_separator === '.' && 3 === price.split( '.' ).length && price[ 0 ] === '.' ) {
2064 + price = price.substr( 1 );
2065 + }
2066 +
2067 + if ( price ) {
2068 + price = maybeUseDecimal( price, currency );
2069 + price = price.split( currency.thousand_separator ).join( '' ).replace( currency.decimal_separator, '.' );
2070 + }
2071 +
2072 + return price;
2073 + }
2074 +
2075 + /**
2076 + * @param {Object} currency The currency object.
2077 + * @return {RegExp} The regular expression object.
2078 + */
2079 + function getRegexForPrice( currency ) {
2080 + let regexString = '[0-9,.';
2081 +
2082 + if ( currency.thousand_separator !== '.' && currency.thousand_separator !== ',' ) {
2083 + regexString += currency.thousand_separator;
2084 + }
2085 + if ( currency.decimal_separator !== '.' && currency.decimal_separator !== ',' ) {
2086 + regexString += currency.decimal_separator;
2087 + }
2088 +
2089 + regexString += ']*\\.?\\,?[0-9]+';
2090 +
2091 + return new RegExp( regexString, 'g' );
2092 + }
2093 +
2094 + /**
2095 + * Maybe replace the decimal separator with the currency's decimal separator.
2096 + *
2097 + * @param {string} price The price string.
2098 + * @param {Object} currency The currency object.
2099 + * @return {string} The modified price string.
2100 + */
2101 + function maybeUseDecimal( price, currency ) {
2102 + let usedForDecimal;
2103 + let priceParts;
2104 + if ( '.' === currency.thousand_separator ) {
2105 + priceParts = price.split( '.' );
2106 + usedForDecimal = 2 === priceParts.length && 2 === priceParts[ 1 ].length;
2107 + if ( usedForDecimal ) {
2108 + price = price.replace( '.', currency.decimal_separator );
2109 + }
2110 + }
2111 + return price;
2112 + }
2113 +
2114 + /**
2115 + * Add trailing zeros to a price if necessary and replace the decimal separator.
2116 + *
2117 + * @param {number|string} price The price to format.
2118 + * @param {Object} currency The currency object containing the decimal separator.
2119 + * @param {boolean} [force=false] Whether to force processing even if the price is not a number.
2120 + * @return {string} The formatted price string.
2121 + */
2122 + function maybeAddTrailingZeroToPrice( price, currency, force = false ) {
2123 + if ( 'number' !== typeof price && ! force ) {
2124 + return price;
2125 + }
2126 +
2127 + price = String( price ); // first convert to string
2128 + const pos = price.indexOf( '.' );
2129 +
2130 + if ( pos === -1 ) {
2131 + price = `${ price }.`;
2132 +
2133 + for ( let n = 0; n < currency.decimals; ++n ) {
2134 + price += '0';
2135 + }
2136 + } else {
2137 + const decimalsString = price.substring( pos + 1 );
2138 + if ( decimalsString.length < currency.decimals ) {
2139 + if ( decimalsString.length < 2 ) {
2140 + price += '0';
2141 + }
2142 +
2143 + for ( let n = 2; n < currency.decimals; ++n ) {
2144 + price += '0';
2145 + }
2146 + }
2147 + }
2148 +
2149 + return price.replace( '.', currency.decimal_separator );
2150 + }
2151 +
2152 + /**
2153 + * Format a numeric string by adding thousand separators.
2154 + *
2155 + * @param {string|number} price The numeric value to format.
2156 + * @param {Object} options Formatting options.
2157 + * @param {string} options.decimal_separator Character used as decimal separator.
2158 + * @param {string} options.thousand_separator Character used as thousand separator.
2159 + *
2160 + * @return {string} The price string with thousand separators.
2161 + */
2162 + function addThousands( price, options ) {
2163 + const split = options.decimal_separator === ''
2164 + ? [ price.toString() ]
2165 + : price.split( options.decimal_separator );
2166 +
2167 + if ( options.thousand_separator ) {
2168 + split[ 0 ] = split[ 0 ].replace( /\B(?=(\d{3})+(?!\d))/g, options.thousand_separator );
2169 + }
2170 +
2171 + return split.join( options.decimal_separator );
2172 + }
2173 +
2174 + /**
2175 + * Maybe remove trailing zeros from a price string.
2176 + *
2177 + * @param {string} price The price string.
2178 + * @param {Object} currency The currency data.
2179 + *
2180 + * @return {string} The price string with trailing zeros removed.
2181 + */
2182 + function maybeRemoveTrailingZerosFromPrice( price, currency ) {
2183 + const split = price.split( currency.decimal_separator );
2184 + if ( 2 !== split.length || split[ 1 ].length <= currency.decimals ) {
2185 + return price;
2186 + }
2187 + if ( 0 === currency.decimals ) {
2188 + return split[ 0 ];
2189 + }
2190 + return `${ split[ 0 ] }${ currency.decimal_separator }${ split[ 1 ].substr( 0, currency.decimals ) }`;
2191 + }
2192 +
1696 2193 return {
1697 - init: function() {
2194 + init() {
1698 2195 jQuery( document ).off( 'submit.formidable', '.frm-show-form' );
1699 2196 jQuery( document ).on( 'submit.formidable', '.frm-show-form', frmFrontForm.submitForm );
1700 2197
1701 - jQuery( '.frm-show-form input[onblur], .frm-show-form textarea[onblur]' ).each( function() {
1702 - if ( jQuery( this ).val() === '' ) {
1703 - jQuery( this ).trigger( 'blur' );
1704 - }
1705 - } );
1706 -
1707 2198 jQuery( document ).on( 'change', '.frm-show-form input[name^="item_meta"], .frm-show-form select[name^="item_meta"], .frm-show-form textarea[name^="item_meta"]', frmFrontForm.fieldValueChanged );
1708 2199
1709 2200 jQuery( document ).on( 'change', '.frm_verify[id^=field_]', onHoneypotFieldChange );
1710 2201
@@ -1731,8 +2222,13 @@
1731 2222 jQuery( document ).on(
1732 2223 'frmPageChanged',
1733 2224 destroyhCaptcha
1734 2225 );
2226 +
2227 + jQuery( document ).on( 'frmAfterAddRow frmAfterRemoveRow', calcProductsTotal );
2228 + jQuery( document ).on( 'change', '[type="checkbox"][data-frmprice],[type="radio"][data-frmprice],[type="hidden"][data-frmprice],select:has([data-frmprice])', calcProductsTotal );
2229 + jQuery( document ).on( 'keyup change', '[data-frmproduct],[type="text"][data-frmprice]', calcProductsTotal );
2230 + calcProductsTotal();
1735 2231 },
1736 2232
1737 2233 getFieldId,
1738 2234
@@ -1742,9 +2238,9 @@
1742 2238 * @param {HTMLElement} captcha
1743 2239 * @param {string} captchaSelector
1744 2240 * @return {void}
1745 2241 */
1746 - renderCaptcha: function( captcha, captchaSelector ) {
2242 + renderCaptcha( captcha, captchaSelector ) {
1747 2243 const rendered = captcha.getAttribute( 'data-rid' ) !== null;
1748 2244 if ( rendered ) {
1749 2245 return;
1750 2246 }
@@ -1751,9 +2247,9 @@
1751 2247
1752 2248 const size = captcha.getAttribute( 'data-size' );
1753 2249 const params = {
1754 2250 sitekey: captcha.getAttribute( 'data-sitekey' ),
1755 - size: size,
2251 + size,
1756 2252 theme: captcha.getAttribute( 'data-theme' )
1757 2253 };
1758 2254
1759 2255 if ( size === 'invisible' ) {
@@ -1769,9 +2265,9 @@
1769 2265 };
1770 2266 }
1771 2267
1772 2268 const activeCaptcha = getSelectedCaptcha( captchaSelector );
1773 - const captchaContainer = typeof turnstile !== 'undefined' && turnstile === activeCaptcha ? '#' + captcha.id : captcha.id;
2269 + const captchaContainer = typeof turnstile !== 'undefined' && turnstile === activeCaptcha ? `#${ captcha.id }` : captcha.id;
1774 2270 const captchaID = activeCaptcha.render( captchaContainer, params );
1775 2271
1776 2272 captcha.setAttribute( 'data-rid', captchaID );
1777 2273
@@ -1777,19 +2273,20 @@
1777 2273
1778 2274 maybeFixCaptchaLabel( captcha );
1779 2275 },
1780 2276
1781 - afterSingleRecaptcha: function() {
1782 - const object = jQuery( '.frm-show-form .g-recaptcha' ).closest( 'form' )[ 0 ];
2277 + afterSingleRecaptcha() {
2278 + const recaptcha = document.querySelector( '.frm-show-form .g-recaptcha' );
2279 + const object = recaptcha ? recaptcha.closest( 'form' ) : null;
1783 2280 frmFrontForm.submitFormNow( object );
1784 2281 },
1785 2282
1786 - afterRecaptcha: function( _, formID ) {
1787 - const object = jQuery( '#frm_form_' + formID + '_container form' )[ 0 ];
2283 + afterRecaptcha( _, formID ) {
2284 + const object = document.querySelector( `#frm_form_${ formID }_container form` );
1788 2285 frmFrontForm.submitFormNow( object );
1789 2286 },
1790 2287
1791 - submitForm: function( e ) {
2288 + submitForm( e ) {
1792 2289 frmFrontForm.submitFormManual( e, this );
1793 2290 },
1794 2291
1795 2292 /**
@@ -1796,21 +2293,10 @@
1796 2293 * @param {Event} e
1797 2294 * @param {HTMLElement} object The form object that is being submitted.
1798 2295 * @return {void}
1799 2296 */
1800 - submitFormManual: function( e, object ) {
1801 - let isPro, errors,
1802 - invisibleRecaptcha = hasInvisibleRecaptcha( object ),
1803 - classList = object.className.trim().split( /\s+/gi );
1804 -
1805 - if ( classList && invisibleRecaptcha.length < 1 ) {
1806 - isPro = classList.indexOf( 'frm_pro_form' ) > -1;
1807 - if ( ! isPro ) {
1808 - return;
1809 - }
1810 - }
1811 -
1812 - if ( jQuery( 'body' ).hasClass( 'wp-admin' ) && jQuery( object ).closest( '.frmapi-form' ).length < 1 ) {
2297 + submitFormManual( e, object ) {
2298 + if ( document.body.classList.contains( 'wp-admin' ) && ! object.closest( '.frmapi-form' ) ) {
1813 2299 return;
1814 2300 }
1815 2301
1816 2302 e.preventDefault();
@@ -1818,14 +2304,16 @@
1818 2304 if ( typeof frmProForm !== 'undefined' && typeof frmProForm.submitAllowed === 'function' && ! frmProForm.submitAllowed( object ) ) {
1819 2305 return;
1820 2306 }
1821 2307
1822 - errors = frmFrontForm.validateFormSubmit( object );
2308 + const errors = frmFrontForm.validateFormSubmit( object );
1823 2309 if ( Object.keys( errors ).length !== 0 ) {
1824 2310 return;
1825 2311 }
1826 2312
1827 - if ( invisibleRecaptcha.length ) {
2313 + const invisibleRecaptcha = hasInvisibleRecaptcha( object );
2314 +
2315 + if ( invisibleRecaptcha ) {
1828 2316 showLoadingIndicator( jQuery( object ) );
1829 2317 executeInvisibleRecaptcha( invisibleRecaptcha );
1830 2318 } else {
1831 2319 showSubmitLoading( jQuery( object ) );
@@ -1833,11 +2321,12 @@
1833 2321 frmFrontForm.submitFormNow( object );
1834 2322 }
1835 2323 },
1836 2324
1837 - submitFormNow: function( object ) {
1838 - let hasFileFields, antispamInput,
1839 - classList = object.className.trim().split( /\s+/gi );
2325 + submitFormNow( object ) {
2326 + let hasFileFields;
2327 + let antispamInput;
2328 + const classList = object.className.trim().split( /\s+/gi );
1840 2329
1841 2330 if ( object.hasAttribute( 'data-token' ) && null === object.querySelector( '[name="antispam_token"]' ) ) {
1842 2331 // include the antispam token on form submit.
1843 2332 antispamInput = document.createElement( 'input' );
@@ -1843,9 +2332,9 @@
1843 2332 antispamInput = document.createElement( 'input' );
1844 2333 antispamInput.type = 'hidden';
1845 2334 antispamInput.name = 'antispam_token';
1846 2335 antispamInput.value = object.getAttribute( 'data-token' );
1847 - object.appendChild( antispamInput );
2336 + object.append( antispamInput );
1848 2337 }
1849 2338
1850 2339 // Add a unique ID, used for duplicate checks.
1851 2340 const uniqueIDInput = document.createElement( 'input' );
@@ -1851,16 +2340,16 @@
1851 2340 const uniqueIDInput = document.createElement( 'input' );
1852 2341 uniqueIDInput.type = 'hidden';
1853 2342 uniqueIDInput.name = 'unique_id';
1854 2343 uniqueIDInput.value = getUniqueKey();
1855 - object.appendChild( uniqueIDInput );
2344 + object.append( uniqueIDInput );
1856 2345
1857 - if ( classList.indexOf( 'frm_ajax_submit' ) > -1 ) {
1858 - hasFileFields = jQuery( object ).find( 'input[type="file"]' ).filter( function() {
1859 - return !! this.value;
1860 - } ).length;
2346 + if ( classList.includes( 'frm_ajax_submit' ) ) {
2347 + const fileInputs = object.querySelectorAll( 'input[type="file"]' );
2348 + hasFileFields = Array.from( fileInputs ).filter( input => !! input.value ).length;
1861 2349 if ( hasFileFields < 1 ) {
1862 - const action = jQuery( object ).find( 'input[name="frm_action"]' ).val();
2350 + const actionInput = object.querySelector( 'input[name="frm_action"]' );
2351 + const action = actionInput ? actionInput.value : '';
1863 2352 frmFrontForm.checkFormErrors( object, action );
1864 2353 } else {
1865 2354 object.submit();
1866 2355 }
@@ -1873,10 +2362,11 @@
1873 2362 * @param {HTMLElement|Object} object Form object. This might be a jQuery object.
1874 2363 *
1875 2364 * @return {Array} List of errors.
1876 2365 */
1877 - validateFormSubmit: function( object ) {
1878 - if ( typeof tinyMCE !== 'undefined' && jQuery( object ).find( '.wp-editor-wrap' ).length ) {
2366 + validateFormSubmit( object ) {
2367 + const form = object instanceof jQuery ? object.get( 0 ) : object;
2368 + if ( typeof tinyMCE !== 'undefined' && form?.querySelector( '.wp-editor-wrap' ) ) {
1879 2369 tinyMCE.triggerSave();
1880 2370 }
1881 2371
1882 2372 jsErrors = [];
@@ -1895,14 +2385,17 @@
1895 2385 /**
1896 2386 * @param {HTMLElement|Object} object Form object. This might be a jQuery object.
1897 2387 * @return {Array} List of errors.
1898 2388 */
1899 - getAjaxFormErrors: function( object ) {
1900 - let customErrors, key;
2389 + getAjaxFormErrors( object ) {
2390 + let customErrors;
2391 + let key;
2392 + const form = object instanceof jQuery ? object.get( 0 ) : object;
1901 2393
1902 2394 jsErrors = validateForm( object );
1903 2395 if ( typeof frmThemeOverride_jsErrors === 'function' ) { // eslint-disable-line camelcase
1904 - const action = jQuery( object ).find( 'input[name="frm_action"]' ).val();
2396 + const actionInput = form ? form.querySelector( 'input[name="frm_action"]' ) : null;
2397 + const action = actionInput ? actionInput.value : '';
1905 2398 customErrors = frmThemeOverride_jsErrors( action, object );
1906 2399 if ( Object.keys( customErrors ).length ) {
1907 2400 for ( key in customErrors ) {
1908 2401 jsErrors[ key ] = customErrors[ key ];
@@ -1921,17 +2414,18 @@
1921 2414 /**
1922 2415 * @param {HTMLElement|Object} object Form object. This might be a jQuery object.
1923 2416 * @return {void}
1924 2417 */
1925 - addAjaxFormErrors: function( object ) {
1926 - let key, $fieldCont;
2418 + addAjaxFormErrors( object ) {
2419 + let key;
2420 + const form = object instanceof jQuery ? object.get( 0 ) : object;
1927 2421 removeAllErrors();
1928 2422
1929 2423 for ( key in jsErrors ) {
1930 - $fieldCont = jQuery( object ).find( '#frm_field_' + key + '_container' );
2424 + const fieldCont = form ? form.querySelector( `#frm_field_${ key }_container` ) : null;
1931 2425
1932 - if ( $fieldCont.length ) {
1933 - addFieldError( $fieldCont, key, jsErrors );
2426 + if ( fieldCont ) {
2427 + addFieldError( fieldCont, key, jsErrors );
1934 2428 } else {
1935 2429 // we are unable to show the error, so remove it
1936 2430 delete jsErrors[ key ];
1937 2431 }
@@ -1945,23 +2439,28 @@
1945 2439 checkRequiredField,
1946 2440 showSubmitLoading,
1947 2441 removeSubmitLoading,
1948 2442
1949 - scrollToID: function( id ) {
2443 + scrollToID( id ) {
1950 2444 const object = jQuery( document.getElementById( id ) );
1951 2445 frmFrontForm.scrollMsg( object, false );
1952 2446 },
1953 2447
1954 - scrollMsg: function( id, object, animate ) {
1955 - let newPos, m, b, screenTop, screenBottom,
1956 - scrollObj = '';
1957 - if ( typeof object === 'undefined' ) {
1958 - scrollObj = jQuery( document.getElementById( 'frm_form_' + id + '_container' ) );
2448 + scrollMsg( id, object, animate ) {
2449 + let newPos;
2450 + let screenTop;
2451 + let screenBottom;
2452 + let scrollObj = '';
2453 +
2454 + if ( object === undefined ) {
2455 + scrollObj = jQuery( document.getElementById( `frm_form_${ id }_container` ) );
1959 2456 if ( scrollObj.length < 1 ) {
1960 2457 return;
1961 2458 }
1962 2459 } else if ( typeof id === 'string' ) {
1963 - scrollObj = jQuery( object ).find( '#frm_field_' + id + '_container' );
2460 + const formEl = object instanceof jQuery ? object.get( 0 ) : object;
2461 + const fieldEl = formEl ? formEl.querySelector( `#frm_field_${ id }_container` ) : null;
2462 + scrollObj = fieldEl ? jQuery( fieldEl ) : jQuery();
1964 2463 } else {
1965 2464 scrollObj = id;
1966 2465 }
1967 2466
@@ -1966,17 +2465,17 @@
1966 2465 }
1967 2466
1968 2467 jQuery( scrollObj ).trigger( 'focus' );
1969 2468 newPos = scrollObj.offset().top;
1970 - if ( ! newPos || frm_js.offset === '-1' ) { // eslint-disable-line camelcase
2469 + if ( ! newPos || frm_js.offset === '-1' ) {
1971 2470 return;
1972 2471 }
1973 - newPos = newPos - frm_js.offset; // eslint-disable-line camelcase
2472 + newPos = newPos - frm_js.offset;
1974 2473
1975 - m = jQuery( 'html' ).css( 'margin-top' );
1976 - b = jQuery( 'body' ).css( 'margin-top' );
1977 - if ( m || b ) {
1978 - newPos = newPos - parseInt( m ) - parseInt( b );
2474 + const docMarginTop = getComputedStyle( document.documentElement ).marginTop;
2475 + const bodyMarginTop = getComputedStyle( document.body ).marginTop;
2476 + if ( docMarginTop || bodyMarginTop ) {
2477 + newPos = newPos - parseInt( docMarginTop ) - parseInt( bodyMarginTop );
1979 2478 }
1980 2479
1981 2480 if ( newPos && window.innerHeight ) {
1982 2481 screenTop = document.documentElement.scrollTop || document.body.scrollTop;
@@ -1983,9 +2482,9 @@
1983 2482 screenBottom = screenTop + window.innerHeight;
1984 2483
1985 2484 if ( newPos > screenBottom || newPos < screenTop ) {
1986 2485 // Not in view
1987 - if ( typeof animate === 'undefined' ) {
2486 + if ( animate === undefined ) {
1988 2487 document.documentElement.scrollTop = newPos;
1989 2488 } else {
1990 2489 animateScroll( screenTop, newPos, 500 );
1991 2490 }
@@ -1993,13 +2492,13 @@
1993 2492 }
1994 2493 }
1995 2494 },
1996 2495
1997 - fieldValueChanged: function( e ) {
2496 + fieldValueChanged( e ) {
1998 2497 /*jshint validthis:true */
1999 2498
2000 2499 const fieldId = frmFrontForm.getFieldId( this, false );
2001 - if ( ! fieldId || typeof fieldId === 'undefined' ) {
2500 + if ( ! fieldId ) {
2002 2501 return;
2003 2502 }
2004 2503
2005 2504 if ( e.frmTriggered && e.frmTriggered == fieldId ) {
@@ -2012,9 +2511,9 @@
2012 2511 maybeValidateChange( this );
2013 2512 }
2014 2513 },
2015 2514
2016 - escapeHtml: function( text ) {
2515 + escapeHtml( text ) {
2017 2516 console.warn( 'DEPRECATED: function frmFrontForm.escapeHtml in v6.17' );
2018 2517 return text
2019 2518 .replace( /&/g, '&amp;' )
2020 2519 .replace( /</g, '&lt;' )
@@ -2022,31 +2521,9 @@
2022 2521 .replace( /"/g, '&quot;' )
2023 2522 .replace( /'/g, '&#039;' );
2024 2523 },
2025 2524
2026 - /**
2027 - * This function was used in old back end code in v2.0.
2028 - *
2029 - * @param {string} classes
2030 - * @return {void}
2031 - */
2032 - invisible: function( classes ) {
2033 - console.warn( 'DEPRECATED: function frmFrontForm.invisible in v6.16.3' );
2034 - jQuery( classes ).css( 'visibility', 'hidden' );
2035 - },
2036 -
2037 - /**
2038 - * This function was used in old back end code in v2.0.
2039 - *
2040 - * @param {string} classes
2041 - * @return {void}
2042 - */
2043 - visible: function( classes ) {
2044 - console.warn( 'DEPRECATED: function frmFrontForm.visible in v6.16.3' );
2045 - jQuery( classes ).css( 'visibility', 'visible' );
2046 - },
2047 -
2048 - triggerCustomEvent: triggerCustomEvent,
2525 + triggerCustomEvent,
2049 2526 documentOn
2050 2527 };
2051 2528 }
2052 2529
@@ -2093,9 +2570,9 @@
2093 2570 const captcha = captchas[ c ];
2094 2571 if ( ! formIsVisible ) {
2095 2572 // If the form is not visible, try again later in 400ms.
2096 2573 // This fixes issues where the form fades visible on page load.
2097 - // Or whne the form is inside of a modal.
2574 + // Or when the form is inside of a modal.
2098 2575 const interval = setInterval(
2099 2576 function() {
2100 2577 if ( closestForm && closestForm.offsetParent !== null ) {
2101 2578 frmFrontForm.renderCaptcha( captcha, captchaSelector );