(function() { // get form element from mpa wp.hooks.addAction('mpa_step_checkout_form', 'mpacf', function ($element) { new mpaCheckoutFields($element); }); class mpaCheckoutFields { /** * @param {Object} $element * * @since 1.0 */ constructor($element) { this.$element = $element; this.$fields = $element.find('.mpa-input-wrapper[class*="mpa-"][class*="-control"] [class^="mpa-customer-"]'); //init phones Array.from(this.$fields).forEach(field => { if (field.getAttribute('type') === 'tel') { mpa_intl_tel_input(jQuery(field)); } }); this.$buttonNext = this.$element.find('.mpa-button-next'); this.addListeners(); //validate fields wp.hooks.addFilter('mpa_step_checkout_form_valid', 'mpacf', ($bool, $currentform) => { let isvalidform = true; Array.from($currentform.find('.mpa-input-wrapper[class*="mpa-"][class*="-control"] [class^="mpa-customer-"]')).forEach(field => { if (!this.validateField(field)) { isvalidform = false; } }); return isvalidform; }); } addListeners() { //fields data to cart this.$buttonNext.on('click', () => { wp.hooks.addFilter('mpa_booking_cart_data', 'mpacf', (cart_data) => { if (!cart_data.hasOwnProperty('checkout_fields')) { cart_data.checkout_fields = {}; } cart_data.checkout_fields = {}; Array.from(this.$fields).forEach(field => { if (this.getFieldValue(field)) { cart_data.checkout_fields[field.getAttribute('name')] = this.getFieldValue(field); } }); return cart_data; }); }); } validateField(field) { switch (field.getAttribute('type')) { case 'email': return field.checkValidity(); case 'country': return field.checkValidity(); case 'date_of_birth': let dob_validity = false; var dayReqControl = jQuery(field).siblings(".mpa-day-control-component[required]"); var monthReqControl = jQuery(field).siblings(".mpa-month-control-component[required]"); var yearReqControl = jQuery(field).siblings(".mpa-year-control-component[required]"); if ( dayReqControl.val() === '' || monthReqControl.val() === '' || yearReqControl.val() === '' ) { dob_validity = false; jQuery(field).focus(); return dob_validity; } dob_validity = true; return dob_validity; case 'tel': let validity = false; if ( ( jQuery(field).is('[required]') && jQuery(field).is('.mpa-phone-number--invalid') ) || ( jQuery(field).is('[required]') && jQuery(field).val() === '') ) { validity = false; return validity; } else { validity = true; return validity; } default: return field.checkValidity(); } } getFieldValue(field) { switch (field.getAttribute('type')) { case 'tel': return jQuery(field).parent().children('input[type="hidden"][name="' + field.name + '"]').val(); break; case 'email': return jQuery(field).val(); break; case 'file': return false; break; case 'checkbox': if (jQuery(field).is(':checked')) { jQuery(field).val('1'); } else { jQuery(field).val('0'); } return jQuery(field).val(); break; default: return jQuery(field).val(); break; } } } })();