const domain = "https://formbuilder.myappgurus.com/api/";
var authUser = 0;
var formData = {};
var currentPageIndex = 0;
let hiddenValues = [];
const formpage = window.location.href;
const forms = document.querySelectorAll('.mag-form');
const myappgurusforms = window.myappgurusforms;
const myappgurussettings = window.myappgurussettings ? JSON.parse(window.myappgurussettings) : null;
const formsData = myappgurusforms ? JSON.parse(myappgurusforms) : null;
if (formsData?.fb_pixel_status == '1') {
let script = ``;
document.head.insertAdjacentHTML('beforeend', script);
}
if (formsData?.bing_status == '1') {
let pixelId = formsData?.bing_pixel_id;
if (pixelId && pixelId !== '' && pixelId !== null) {
let script = ``;
document.head.insertAdjacentHTML('beforeend', script);
}
}
let subdomain = formsData?.shop_name;
subdomain = subdomain?.replace(/[-,\s]/g, '_');
// subdomain = subdomain?.replace(/[^a-zA-Z0-9_]/g, '_');
const data = formsData && formsData.form_data ? JSON.parse(formsData.form_data) : null;
const settings = formsData && formsData.form_settings ? JSON.parse(formsData.form_settings) : null;
const appearance = formsData && formsData.form_appearance ? JSON.parse(formsData.form_appearance) : null;
const afterSubmit = formsData && formsData.form_after_submit ? JSON.parse(formsData.form_after_submit) : null;
const formStatus = (formsData && formsData.form_status !== undefined) ? formsData.form_status : '0';
const reCaptcha = (formsData && formsData.reCaptcha) ? JSON.parse(formsData.reCaptcha) : null;
const removeWatermark = myappgurussettings?.remove_watermark;
const formName = formsData && formsData.form_title ? formsData.form_title : null;
if (myappgurussettings?.custom_css !== null && myappgurussettings?.custom_css !== undefined) {
const styleElement = document.createElement('style');
styleElement.innerHTML = myappgurussettings.custom_css;
document.head.appendChild(styleElement);
}
if (reCaptcha?.recaptcha_status == '1' && myappgurussettings?.recaptcha_type == 'v2') {
const recaptchaScript = document.createElement("script");
recaptchaScript.src = "https://www.google.com/recaptcha/enterprise.js?onload=reCaptchaCallback&render=explicit";
recaptchaScript.async = true;
recaptchaScript.defer = true;
recaptchaScript.id = "recaptcha-script";
document.head.insertAdjacentElement("beforeend", recaptchaScript);
}
if (settings?.CustomJavascript) {
const customScript = document.createElement("script");
customScript.innerHTML = settings.CustomJavascript;
document.head.insertAdjacentElement("beforeend", customScript);
}
const reCaptchaCallbackv3 = () => {
grecaptcha.ready(async () => {
try {
const token = await grecaptcha.execute(myappgurussettings?.recaptcha_site_key, { action: 'submit' });
} catch (error) {
console.error('Error executing reCAPTCHA:', error);
}
});
}
if (reCaptcha?.recaptcha_status == '1' && myappgurussettings?.recaptcha_type == 'v3') {
const recaptchaScript = document.createElement("script");
recaptchaScript.id = 'recaptcha-scriptv3';
recaptchaScript.src = `https://www.google.com/recaptcha/api.js?render=${myappgurussettings?.recaptcha_site_key}`;
recaptchaScript.setAttribute('async', true);
recaptchaScript.setAttribute('defer', true);
document.head.insertAdjacentElement("beforeend", recaptchaScript);
}
const rgbToHex = (r, g, b) => {
const toHex = (x) => x.toString(16).padStart(2, '0').toUpperCase();
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
};
const hsbToHex = (hsb) => {
const { r, g, b } = hsbToRgb(hsb);
return rgbToHex(r, g, b);
};
const hsbToRgb = ({ hue = 0, saturation = 0, brightness = 0 } = {}) => {
const h = hue % 360;
const s = saturation;
const br = brightness;
const c = br * s;
const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
const m = br - c;
let r = 0, g = 0, b = 0;
if (0 <= h && h < 60) {
r = c; g = x; b = 0;
} else if (60 <= h && h < 120) {
r = x; g = c; b = 0;
} else if (120 <= h && h < 180) {
r = 0; g = c; b = x;
} else if (180 <= h && h < 240) {
r = 0; g = x; b = c;
} else if (240 <= h && h < 300) {
r = x; g = 0; b = c;
} else if (300 <= h && h < 360) {
r = c; g = 0; b = x;
}
return {
r: Math.round((r + m) * 255),
g: Math.round((g + m) * 255),
b: Math.round((b + m) * 255)
};
};
const rootForCssVariables = document.documentElement;
const textColorRgb = hsbToHex(appearance?.color?.text);
const buttonColorRgb = hsbToHex(appearance?.color?.button);
const buttonLabelColorRgb = hsbToHex(appearance?.color?.buttonLabel);
const outlineButtonColorRgb = hsbToHex(appearance?.color?.outlineButton);
const backgroundColorRgb = hsbToHex(appearance?.color?.background);
rootForCssVariables.style.setProperty('--mag-text-color', textColorRgb);
rootForCssVariables.style.setProperty('--mag-btn-text-color', buttonLabelColorRgb);
rootForCssVariables.style.setProperty('--mag-btn-bg-color', buttonColorRgb);
rootForCssVariables.style.setProperty('--mag-bg-color', backgroundColorRgb);
rootForCssVariables.style.setProperty('--mag-outline-btn-color', outlineButtonColorRgb);
var bodyTag = document.querySelector('body');
if (afterSubmit !== null) {
var afterSubmitMessage = `
`;
bodyTag.insertAdjacentHTML('afterbegin', afterSubmitMessage);
}
else {
var popupData = `
`;
bodyTag.insertAdjacentHTML('afterbegin', popupData);
}
var errorToast = `
You've already submitted this form using this email address.
`;
bodyTag.insertAdjacentHTML('afterbegin', errorToast);
const countries = [
{ label: 'None', value: '' },
{ label: 'Afghanistan', value: 'AF' },
{ label: 'Albania', value: 'AL' },
{ label: 'Algeria', value: 'DZ' },
{ label: 'Andorra', value: 'AD' },
{ label: 'Angola', value: 'AO' },
{ label: 'Antigua and Barbuda', value: 'AG' },
{ label: 'Argentina', value: 'AR' },
{ label: 'Armenia', value: 'AM' },
{ label: 'Australia', value: 'AU' },
{ label: 'Austria', value: 'AT' },
{ label: 'Azerbaijan', value: 'AZ' },
{ label: 'Bahamas', value: 'BS' },
{ label: 'Bahrain', value: 'BH' },
{ label: 'Bangladesh', value: 'BD' },
{ label: 'Barbados', value: 'BB' },
{ label: 'Belarus', value: 'BY' },
{ label: 'Belgium', value: 'BE' },
{ label: 'Belize', value: 'BZ' },
{ label: 'Benin', value: 'BJ' },
{ label: 'Bhutan', value: 'BT' },
{ label: 'Bolivia', value: 'BO' },
{ label: 'Bosnia and Herzegovina', value: 'BA' },
{ label: 'Botswana', value: 'BW' },
{ label: 'Brazil', value: 'BR' },
{ label: 'Brunei', value: 'BN' },
{ label: 'Bulgaria', value: 'BG' },
{ label: 'Burkina Faso', value: 'BF' },
{ label: 'Burundi', value: 'BI' },
{ label: 'Cabo Verde', value: 'CV' },
{ label: 'Cambodia', value: 'KH' },
{ label: 'Cameroon', value: 'CM' },
{ label: 'Canada', value: 'CA' },
{ label: 'Central African Republic', value: 'CF' },
{ label: 'Chad', value: 'TD' },
{ label: 'Chile', value: 'CL' },
{ label: 'China', value: 'CN' },
{ label: 'Colombia', value: 'CO' },
{ label: 'Comoros', value: 'KM' },
{ label: 'Congo (Congo-Brazzaville)', value: 'CG' },
{ label: 'Costa Rica', value: 'CR' },
{ label: 'Croatia', value: 'HR' },
{ label: 'Cuba', value: 'CU' },
{ label: 'Cyprus', value: 'CY' },
{ label: 'Czechia (Czech Republic)', value: 'CZ' },
{ label: 'Democratic Republic of the Congo', value: 'CD' },
{ label: 'Denmark', value: 'DK' },
{ label: 'Djibouti', value: 'DJ' },
{ label: 'Dominica', value: 'DM' },
{ label: 'Dominican Republic', value: 'DO' },
{ label: 'Ecuador', value: 'EC' },
{ label: 'Egypt', value: 'EG' },
{ label: 'El Salvador', value: 'SV' },
{ label: 'Equatorial Guinea', value: 'GQ' },
{ label: 'Eritrea', value: 'ER' },
{ label: 'Estonia', value: 'EE' },
{ label: 'Eswatini (fmr. "Swaziland")', value: 'SZ' },
{ label: 'Ethiopia', value: 'ET' },
{ label: 'Fiji', value: 'FJ' },
{ label: 'Finland', value: 'FI' },
{ label: 'France', value: 'FR' },
{ label: 'Gabon', value: 'GA' },
{ label: 'Gambia', value: 'GM' },
{ label: 'Georgia', value: 'GE' },
{ label: 'Germany', value: 'DE' },
{ label: 'Ghana', value: 'GH' },
{ label: 'Greece', value: 'GR' },
{ label: 'Grenada', value: 'GD' },
{ label: 'Guatemala', value: 'GT' },
{ label: 'Guinea', value: 'GN' },
{ label: 'Guinea-Bissau', value: 'GW' },
{ label: 'Guyana', value: 'GY' },
{ label: 'Haiti', value: 'HT' },
{ label: 'Holy See', value: 'VA' },
{ label: 'Honduras', value: 'HN' },
{ label: 'Hungary', value: 'HU' },
{ label: 'Iceland', value: 'IS' },
{ label: 'India', value: 'IN' },
{ label: 'Indonesia', value: 'ID' },
{ label: 'Iran', value: 'IR' },
{ label: 'Iraq', value: 'IQ' },
{ label: 'Ireland', value: 'IE' },
{ label: 'Israel', value: 'IL' },
{ label: 'Italy', value: 'IT' },
{ label: 'Jamaica', value: 'JM' },
{ label: 'Japan', value: 'JP' },
{ label: 'Jordan', value: 'JO' },
{ label: 'Kazakhstan', value: 'KZ' },
{ label: 'Kenya', value: 'KE' },
{ label: 'Kiribati', value: 'KI' },
{ label: 'Kuwait', value: 'KW' },
{ label: 'Kyrgyzstan', value: 'KG' },
{ label: 'Laos', value: 'LA' },
{ label: 'Latvia', value: 'LV' },
{ label: 'Lebanon', value: 'LB' },
{ label: 'Lesotho', value: 'LS' },
{ label: 'Liberia', value: 'LR' },
{ label: 'Libya', value: 'LY' },
{ label: 'Liechtenstein', value: 'LI' },
{ label: 'Lithuania', value: 'LT' },
{ label: 'Luxembourg', value: 'LU' },
{ label: 'Madagascar', value: 'MG' },
{ label: 'Malawi', value: 'MW' },
{ label: 'Malaysia', value: 'MY' },
{ label: 'Maldives', value: 'MV' },
{ label: 'Mali', value: 'ML' },
{ label: 'Malta', value: 'MT' },
{ label: 'Marshall Islands', value: 'MH' },
{ label: 'Mauritania', value: 'MR' },
{ label: 'Mauritius', value: 'MU' },
{ label: 'Mexico', value: 'MX' },
{ label: 'Micronesia', value: 'FM' },
{ label: 'Moldova', value: 'MD' },
{ label: 'Monaco', value: 'MC' },
{ label: 'Mongolia', value: 'MN' },
{ label: 'Montenegro', value: 'ME' },
{ label: 'Morocco', value: 'MA' },
{ label: 'Mozambique', value: 'MZ' },
{ label: 'Myanmar (formerly Burma)', value: 'MM' },
{ label: 'Namibia', value: 'NA' },
{ label: 'Nauru', value: 'NR' },
{ label: 'Nepal', value: 'NP' },
{ label: 'Netherlands', value: 'NL' },
{ label: 'New Zealand', value: 'NZ' },
{ label: 'Nicaragua', value: 'NI' },
{ label: 'Niger', value: 'NE' },
{ label: 'Nigeria', value: 'NG' },
{ label: 'North Korea', value: 'KP' },
{ label: 'North Macedonia', value: 'MK' },
{ label: 'Norway', value: 'NO' },
{ label: 'Oman', value: 'OM' },
{ label: 'Pakistan', value: 'PK' },
{ label: 'Palau', value: 'PW' },
{ label: 'Palestine State', value: 'PS' },
{ label: 'Panama', value: 'PA' },
{ label: 'Papua New Guinea', value: 'PG' },
{ label: 'Paraguay', value: 'PY' },
{ label: 'Peru', value: 'PE' },
{ label: 'Philippines', value: 'PH' },
{ label: 'Poland', value: 'PL' },
{ label: 'Portugal', value: 'PT' },
{ label: 'Qatar', value: 'QA' },
{ label: 'Romania', value: 'RO' },
{ label: 'Russia', value: 'RU' },
{ label: 'Rwanda', value: 'RW' },
{ label: 'Saint Kitts and Nevis', value: 'KN' },
{ label: 'Saint Lucia', value: 'LC' },
{ label: 'Saint Vincent and the Grenadines', value: 'VC' },
{ label: 'Samoa', value: 'WS' },
{ label: 'San Marino', value: 'SM' },
{ label: 'Sao Tome and Principe', value: 'ST' },
{ label: 'Saudi Arabia', value: 'SA' },
{ label: 'Senegal', value: 'SN' },
{ label: 'Serbia', value: 'RS' },
{ label: 'Seychelles', value: 'SC' },
{ label: 'Sierra Leone', value: 'SL' },
{ label: 'Singapore', value: 'SG' },
{ label: 'Slovakia', value: 'SK' },
{ label: 'Slovenia', value: 'SI' },
{ label: 'Solomon Islands', value: 'SB' },
{ label: 'Somalia', value: 'SO' },
{ label: 'South Africa', value: 'ZA' },
{ label: 'South Korea', value: 'KR' },
{ label: 'South Sudan', value: 'SS' },
{ label: 'Spain', value: 'ES' },
{ label: 'Sri Lanka', value: 'LK' },
{ label: 'Sudan', value: 'SD' },
{ label: 'Suriname', value: 'SR' },
{ label: 'Sweden', value: 'SE' },
{ label: 'Switzerland', value: 'CH' },
{ label: 'Syria', value: 'SY' },
{ label: 'Tajikistan', value: 'TJ' },
{ label: 'Tanzania', value: 'TZ' },
{ label: 'Thailand', value: 'TH' },
{ label: 'Timor-Leste', value: 'TL' },
{ label: 'Togo', value: 'TG' },
{ label: 'Tonga', value: 'TO' },
{ label: 'Trinidad and Tobago', value: 'TT' },
{ label: 'Tunisia', value: 'TN' },
{ label: 'Turkey', value: 'TR' },
{ label: 'Turkmenistan', value: 'TM' },
{ label: 'Tuvalu', value: 'TV' },
{ label: 'Uganda', value: 'UG' },
{ label: 'Ukraine', value: 'UA' },
{ label: 'United Arab Emirates', value: 'AE' },
{ label: 'United Kingdom', value: 'GB' },
{ label: 'United States of America', value: 'US' },
{ label: 'Uruguay', value: 'UY' },
{ label: 'Uzbekistan', value: 'UZ' },
{ label: 'Vanuatu', value: 'VU' },
{ label: 'Venezuela', value: 'VE' },
{ label: 'Vietnam', value: 'VN' },
{ label: 'Yemen', value: 'YE' },
{ label: 'Zambia', value: 'ZM' },
{ label: 'Zimbabwe', value: 'ZW' }
];
const countriesForAdd = [
{ label: 'None', value: '' },
{ label: 'Afghanistan', value: 'Afghanistan' },
{ label: 'Albania', value: 'Albania' },
{ label: 'Algeria', value: 'Algeria' },
{ label: 'Andorra', value: 'Andorra' },
{ label: 'Angola', value: 'Angola' },
{ label: 'Antigua and Barbuda', value: 'Antigua and Barbuda' },
{ label: 'Argentina', value: 'Argentina' },
{ label: 'Armenia', value: 'Armenia' },
{ label: 'Australia', value: 'Australia' },
{ label: 'Austria', value: 'Austria' },
{ label: 'Azerbaijan', value: 'Azerbaijan' },
{ label: 'Bahamas', value: 'Bahamas' },
{ label: 'Bahrain', value: 'Bahrain' },
{ label: 'Bangladesh', value: 'Bangladesh' },
{ label: 'Barbados', value: 'Barbados' },
{ label: 'Belarus', value: 'Belarus' },
{ label: 'Belgium', value: 'Belgium' },
{ label: 'Belize', value: 'Belize' },
{ label: 'Benin', value: 'Benin' },
{ label: 'Bhutan', value: 'Bhutan' },
{ label: 'Bolivia', value: 'Bolivia' },
{ label: 'Bosnia and Herzegovina', value: 'Bosnia and Herzegovina' },
{ label: 'Botswana', value: 'Botswana' },
{ label: 'Brazil', value: 'Brazil' },
{ label: 'Brunei', value: 'Brunei' },
{ label: 'Bulgaria', value: 'Bulgaria' },
{ label: 'Burkina Faso', value: 'Burkina Faso' },
{ label: 'Burundi', value: 'Burundi' },
{ label: 'Cabo Verde', value: 'Cabo Verde' },
{ label: 'Cambodia', value: 'Cambodia' },
{ label: 'Cameroon', value: 'Cameroon' },
{ label: 'Canada', value: 'Canada' },
{ label: 'Central African Republic', value: 'Central African Republic' },
{ label: 'Chad', value: 'Chad' },
{ label: 'Chile', value: 'Chile' },
{ label: 'China', value: 'China' },
{ label: 'Colombia', value: 'Colombia' },
{ label: 'Comoros', value: 'Comoros' },
{ label: 'Congo (Congo-Brazzaville)', value: 'Congo (Congo-Brazzaville' },
{ label: 'Costa Rica', value: 'Costa Rica' },
{ label: 'Croatia', value: 'Croatia' },
{ label: 'Cuba', value: 'Cuba' },
{ label: 'Cyprus', value: 'Cyprus' },
{ label: 'Czechia (Czech Republic)', value: 'Czechia (Czech Republic' },
{ label: 'Democratic Republic of the Congo', value: 'Democratic Republic of the Congo' },
{ label: 'Denmark', value: 'Denmark' },
{ label: 'Djibouti', value: 'Djibouti' },
{ label: 'Dominica', value: 'Dominica' },
{ label: 'Dominican Republic', value: 'Dominican Republic' },
{ label: 'Ecuador', value: 'Ecuador' },
{ label: 'Egypt', value: 'Egypt' },
{ label: 'El Salvador', value: 'El Salvador' },
{ label: 'Equatorial Guinea', value: 'Equatorial Guinea' },
{ label: 'Eritrea', value: 'Eritrea' },
{ label: 'Estonia', value: 'Estonia' },
{ label: 'Eswatini (fmr. "Swaziland")', value: 'Eswatini (fmr. "Swaziland' },
{ label: 'Ethiopia', value: 'Ethiopia' },
{ label: 'Fiji', value: 'Fiji' },
{ label: 'Finland', value: 'Finland' },
{ label: 'France', value: 'France' },
{ label: 'Gabon', value: 'Gabon' },
{ label: 'Gambia', value: 'Gambia' },
{ label: 'Georgia', value: 'Georgia' },
{ label: 'Germany', value: 'Germany' },
{ label: 'Ghana', value: 'Ghana' },
{ label: 'Greece', value: 'Greece' },
{ label: 'Grenada', value: 'Grenada' },
{ label: 'Guatemala', value: 'Guatemala' },
{ label: 'Guinea', value: 'Guinea' },
{ label: 'Guinea-Bissau', value: 'Guinea-Bissau' },
{ label: 'Guyana', value: 'Guyana' },
{ label: 'Haiti', value: 'Haiti' },
{ label: 'Holy See', value: 'Holy See' },
{ label: 'Honduras', value: 'Honduras' },
{ label: 'Hungary', value: 'Hungary' },
{ label: 'Iceland', value: 'Iceland' },
{ label: 'India', value: 'India' },
{ label: 'Indonesia', value: 'Indonesia' },
{ label: 'Iran', value: 'Iran' },
{ label: 'Iraq', value: 'Iraq' },
{ label: 'Ireland', value: 'Ireland' },
{ label: 'Israel', value: 'Israel' },
{ label: 'Italy', value: 'Italy' },
{ label: 'Jamaica', value: 'Jamaica' },
{ label: 'Japan', value: 'Japan' },
{ label: 'Jordan', value: 'Jordan' },
{ label: 'Kazakhstan', value: 'Kazakhstan' },
{ label: 'Kenya', value: 'Kenya' },
{ label: 'Kiribati', value: 'Kiribati' },
{ label: 'Kuwait', value: 'Kuwait' },
{ label: 'Kyrgyzstan', value: 'Kyrgyzstan' },
{ label: 'Laos', value: 'Laos' },
{ label: 'Latvia', value: 'Latvia' },
{ label: 'Lebanon', value: 'Lebanon' },
{ label: 'Lesotho', value: 'Lesotho' },
{ label: 'Liberia', value: 'Liberia' },
{ label: 'Libya', value: 'Libya' },
{ label: 'Liechtenstein', value: 'Liechtenstein' },
{ label: 'Lithuania', value: 'Lithuania' },
{ label: 'Luxembourg', value: 'Luxembourg' },
{ label: 'Madagascar', value: 'Madagascar' },
{ label: 'Malawi', value: 'Malawi' },
{ label: 'Malaysia', value: 'Malaysia' },
{ label: 'Maldives', value: 'Maldives' },
{ label: 'Mali', value: 'Mali' },
{ label: 'Malta', value: 'Malta' },
{ label: 'Marshall Islands', value: 'Marshall Islands' },
{ label: 'Mauritania', value: 'Mauritania' },
{ label: 'Mauritius', value: 'Mauritius' },
{ label: 'Mexico', value: 'Mexico' },
{ label: 'Micronesia', value: 'Micronesia' },
{ label: 'Moldova', value: 'Moldova' },
{ label: 'Monaco', value: 'Monaco' },
{ label: 'Mongolia', value: 'Mongolia' },
{ label: 'Montenegro', value: 'Montenegro' },
{ label: 'Morocco', value: 'Morocco' },
{ label: 'Mozambique', value: 'Mozambique' },
{ label: 'Myanmar (formerly Burma)', value: 'Myanmar (formerly Burma' },
{ label: 'Namibia', value: 'Namibia' },
{ label: 'Nauru', value: 'Nauru' },
{ label: 'Nepal', value: 'Nepal' },
{ label: 'Netherlands', value: 'Netherlands' },
{ label: 'New Zealand', value: 'New Zealand' },
{ label: 'Nicaragua', value: 'Nicaragua' },
{ label: 'Niger', value: 'Niger' },
{ label: 'Nigeria', value: 'Nigeria' },
{ label: 'North Korea', value: 'North Korea' },
{ label: 'North Macedonia', value: 'North Macedonia' },
{ label: 'Norway', value: 'Norway' },
{ label: 'Oman', value: 'Oman' },
{ label: 'Pakistan', value: 'Pakistan' },
{ label: 'Palau', value: 'Palau' },
{ label: 'Palestine State', value: 'Palestine State' },
{ label: 'Panama', value: 'Panama' },
{ label: 'Papua New Guinea', value: 'Papua New Guinea' },
{ label: 'Paraguay', value: 'Paraguay' },
{ label: 'Peru', value: 'Peru' },
{ label: 'Philippines', value: 'Philippines' },
{ label: 'Poland', value: 'Poland' },
{ label: 'Portugal', value: 'Portugal' },
{ label: 'Qatar', value: 'Qatar' },
{ label: 'Romania', value: 'Romania' },
{ label: 'Russia', value: 'Russia' },
{ label: 'Rwanda', value: 'Rwanda' },
{ label: 'Saint Kitts and Nevis', value: 'Saint Kitts and Nevis' },
{ label: 'Saint Lucia', value: 'Saint Lucia' },
{ label: 'Saint Vincent and the Grenadines', value: 'Saint Vincent and the Grenadines' },
{ label: 'Samoa', value: 'Samoa' },
{ label: 'San Marino', value: 'San Marino' },
{ label: 'Sao Tome and Principe', value: 'Sao Tome and Principe' },
{ label: 'Saudi Arabia', value: 'Saudi Arabia' },
{ label: 'Senegal', value: 'Senegal' },
{ label: 'Serbia', value: 'Serbia' },
{ label: 'Seychelles', value: 'Seychelles' },
{ label: 'Sierra Leone', value: 'Sierra Leone' },
{ label: 'Singapore', value: 'Singapore' },
{ label: 'Slovakia', value: 'Slovakia' },
{ label: 'Slovenia', value: 'Slovenia' },
{ label: 'Solomon Islands', value: 'Solomon Islands' },
{ label: 'Somalia', value: 'Somalia' },
{ label: 'South Africa', value: 'South Africa' },
{ label: 'South Korea', value: 'South Korea' },
{ label: 'South Sudan', value: 'South Sudan' },
{ label: 'Spain', value: 'Spain' },
{ label: 'Sri Lanka', value: 'Sri Lanka' },
{ label: 'Sudan', value: 'Sudan' },
{ label: 'Suriname', value: 'Suriname' },
{ label: 'Sweden', value: 'Sweden' },
{ label: 'Switzerland', value: 'Switzerland' },
{ label: 'Syria', value: 'Syria' },
{ label: 'Tajikistan', value: 'Tajikistan' },
{ label: 'Tanzania', value: 'Tanzania' },
{ label: 'Thailand', value: 'Thailand' },
{ label: 'Timor-Leste', value: 'Timor-Leste' },
{ label: 'Togo', value: 'Togo' },
{ label: 'Tonga', value: 'Tonga' },
{ label: 'Trinidad and Tobago', value: 'Trinidad and Tobago' },
{ label: 'Tunisia', value: 'Tunisia' },
{ label: 'Turkey', value: 'Turkey' },
{ label: 'Turkmenistan', value: 'Turkmenistan' },
{ label: 'Tuvalu', value: 'Tuvalu' },
{ label: 'Uganda', value: 'Uganda' },
{ label: 'Ukraine', value: 'Ukraine' },
{ label: 'United Arab Emirates', value: 'United Arab Emirates' },
{ label: 'United Kingdom', value: 'United Kingdom' },
{ label: 'United States of America', value: 'United States of America' },
{ label: 'Uruguay', value: 'Uruguay' },
{ label: 'Uzbekistan', value: 'Uzbekistan' },
{ label: 'Vanuatu', value: 'Vanuatu' },
{ label: 'Venezuela', value: 'Venezuela' },
{ label: 'Vietnam', value: 'Vietnam' },
{ label: 'Yemen', value: 'Yemen' },
{ label: 'Zambia', value: 'Zambia' },
{ label: 'Zimbabwe', value: 'Zimbabwe' }
];
const jsonToHtml = {
EmailInput: 'email',
NameInput: 'text',
TelephoneInput: 'tel',
PasswordInput: 'password',
URLInput: 'url',
DatePickerInput: 'date',
TimePickerInput: 'time',
HiddenInput: 'hidden',
SignatureInput: 'file',
DividerInput: 'html',
TextInput: 'text',
RadioInput: 'radio',
CheckboxInput: 'checkbox',
RangeBarInput: 'range',
AcceptTermsInput: 'checkbox',
ButtonInput: 'button',
ImageOptionsInput: 'text',
ColorInput: 'color',
ColorSwatchInput: 'radio',
FileInput: 'file',
NumberInput: 'number'
}
if (document.querySelector('#okBtn')) {
document.querySelector('#okBtn').addEventListener('click', () => {
document.querySelector('.modal-dialog.modal-confirm').style.display = 'none';
document.querySelector('.back-shadow').style.display = 'none';
bodyTag.classList.remove('mag-overflow');
});
}
document.addEventListener("DOMContentLoaded", async () => {
if (__st.p == 'product') {
fd = new FormData();
fd.append('shopName', Shopify.shop);
fetch(`${domain}getCustomizeData`, {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: fd
})
.then(res => res.json())
.then(response => {
if (response.notify_me == '1') {
var notifyMeForm = () => {
let magNotifyMeForm = document.querySelector('form#mag-notify-form'),
notifymeForm = document.querySelector('.mag-notifyme-form'),
product = document.querySelector('#mag-pro-details').textContent,
varId = notifymeForm.getAttribute('data-varid'),
proQty = notifymeForm.getAttribute('data-inventory-quantity');
if (notifymeForm && !magNotifyMeForm) {
if (product) {
if (proQty == 0) {
let html = ``;
notifymeForm.innerHTML = html;
let notifyForm = document.querySelector('#mag-notify-form');
if (notifyForm) {
notifyForm.addEventListener('submit', (e) => {
e.preventDefault();
let fd = new FormData(notifyForm),
email = document.querySelector('[name="email"]').value;
fd.append('shopName', Shopify.shop);
fd.append('varId', varId);
if (email.trim() != '') {
document.querySelector('.mag-input-group__btn').classList.add('notify-load');
document.querySelector('.mag-email-error').classList.add('hide');
fetch(`${domain}notifyme`, {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: fd
})
.then(res => res.json())
.then(response => {
if (response != '0') {
notifyForm.reset();
document.querySelector('.mag-input-group__btn').classList.remove('notify-load');
document.querySelector('.mag-notify-me-success-msg').classList.remove('hide');
setTimeout(() => {
document.querySelector('.mag-notify-me-success-msg').classList.add('hide');
}, 3000);
}
});
} else {
document.querySelector('.mag-email-error').classList.remove('hide');
}
});
}
}
}
} else {
if (proQty > 0) {
let removeForm = document.querySelector('.mag-notify-input-group');
if (removeForm) {
removeForm.remove();
}
}
}
}
notifyMeForm();
var varId = document.querySelector('[name="id"]');
var observer = new MutationObserver(() => {
let proData = document.querySelector('#mag-pro-details').textContent,
proVarId = varId.value,
varData = JSON.parse(proData).filter(item => item.id == proVarId),
magFormData = document.querySelector('.mag-notifyme-form');
magFormData.setAttribute('data-varid', varData[0].id);
magFormData.setAttribute('data-inventory-quantity', (varData[0].available == false) ? '0' : '1');
notifyMeForm();
});
var observerConfig = { childList: true, subtree: true, attributes: true, };
observer.observe(varId, observerConfig);
}
});
}
});
const authenticate = (shop) => {
fetch(`${domain}authShop`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
shop: shop
})
})
.then(res => res.json())
.then(response => {
if (response == 1) {
authUser = 1;
}
formAppend(`${domain}`);
})
}
const formAppend = (Domain) => {
if (!formsData || formsData.length === 0 || formStatus == 0) {
var customer_data = [],
cid = __st.cid;
if (__st.cid != undefined) {
var cdata = new FormData();
cdata.append('customer_id', cid);
cdata.append('shop', Shopify.shop);
fetch(`${Domain}getCustomer`, {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: cdata,
})
.then(res => res.json())
.then(response => {
customer_data.push(response);
})
}
var formData = forms;
formData.forEach(curr => {
var formToken = curr.getAttribute('data-token'),
url = curr.getAttribute('data-url');
fetch(`${Domain}getFormData?token=${formToken}&shop=${Shopify.shop}&url=${url}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
})
.then(res => res.json())
.then(response => {
if (response[0].form_title != undefined && response[0].form_code != undefined && response[0].form_status == '1') {
if (authUser == 0) {
curr.innerHTML += `${response[0].form_title}
`;
curr.innerHTML += `
${response[0].form_code}
Please upgrade the plan.
`;
} else if (response[1].disable_form == 'disabled') {
curr.innerHTML += `${response[0].form_title}
`;
curr.innerHTML += `
${response[0].form_code}
Exceeded form submission limits. Please upgrade the plan.
`;
} else {
curr.innerHTML += `${response[0].form_title}
`;
curr.innerHTML += response[0].form_code;
}
if (removeWatermark == '1') {
curr.innerHTML += ``;
} else {
curr.innerHTML += ``;
}
var formDataSubmit = curr.querySelector(`.mag-form[data-token="${formToken}"] #submitForm`),
labelText = curr.querySelectorAll(`.mag-form[data-token="${formToken}"] #submitForm .el-input-label`);
formDataSubmit.addEventListener('submit', (e) => {
e.preventDefault();
var loginButtonText = e.currentTarget.querySelector('button[type="submit"]').innerHTML,
fileSizeCount = 0;
e.currentTarget.querySelector('button[type="submit"]').innerHTML = `Submitting..`;
e.currentTarget.querySelector('button[type="submit"]').setAttribute('disabled', 'disabled')
const form = new FormData();
form.append('formToken', formToken);
labelText.forEach(current => {
if (current.parentElement.nextElementSibling.nodeName == 'INPUT') {
if (current.parentElement.nextElementSibling.getAttribute('type') == 'file') {
var fileErrorMessageId = current.getAttribute('data-id');
if (current.parentElement.nextElementSibling.files[0]) {
if (response[1].free_plan == 1) {
if (current.parentElement.nextElementSibling.files[0].size > 2000000) {
var appendDiv = e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`);
if (appendDiv != null) {
appendDiv.innerHTML = 'File size must be less then 2MB for upload.';
fileSizeCount += 1;
} else {
current.parentElement.nextElementSibling.insertAdjacentHTML('afterend', `File size must be less then 2MB for upload.
`);
fileSizeCount += 1;
}
} else {
if (e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`)) {
e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`).remove();
}
}
} else {
if (current.parentElement.nextElementSibling.files[0].size > 20000000) {
var appendDiv = e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`);
if (appendDiv != null) {
appendDiv.innerHTML = 'File size must be less then 20MB for upload.';
fileSizeCount += 1;
} else {
current.parentElement.nextElementSibling.insertAdjacentHTML('afterend', `File size must be less then 20MB for upload.
`);
fileSizeCount += 1;
}
} else {
if (e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`)) {
e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`).remove();
}
}
}
} else {
if (e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`)) {
e.currentTarget.querySelector(`.mag-file-validation-msg[data-id="${fileErrorMessageId}"]`).remove();
}
}
form.append(current.innerHTML, current.parentElement.nextElementSibling.files[0]);
} else if (current.parentElement.nextElementSibling.getAttribute('type') == 'email') {
form.append('customer_email', current.parentElement.nextElementSibling.value);
form.append('cust_email', current.parentElement.nextElementSibling.value);
form.append(current.innerHTML, current.parentElement.nextElementSibling.value);
if (window.uetq) {
window.uetq.push("event", "form_submit", {
event_category: formName,
event_label: "Form Submission",
user_email: current.parentElement.nextElementSibling.value
});
}
} else if (current.parentElement.nextElementSibling.getAttribute('type') == 'tel') {
form.append('phone', current.parentElement.nextElementSibling.value);
form.append(current.innerHTML, current.parentElement.nextElementSibling.value);
} else {
form.append(current.innerHTML, current.parentElement.nextElementSibling.value);
}
} else if (current.parentElement.nextElementSibling.nodeName == 'TEXTAREA') {
form.append(current.innerHTML, current.parentElement.nextElementSibling.value);
} else if (current.parentElement.nextElementSibling.nodeName == 'SELECT') {
form.append(current.innerHTML, current.parentElement.nextElementSibling.value);
} else {
if (current.parentElement.nextElementSibling.firstElementChild.firstElementChild.getAttribute('type') == 'radio') {
var radioButtonData = '',
radioButton = current.parentElement.nextElementSibling.querySelectorAll('.form-check.radio');
radioButton.forEach(curr => {
if (curr.firstElementChild.checked == true) {
radioButtonData = curr.firstElementChild.value;
}
});
form.append(current.innerHTML, radioButtonData);
} else {
var checkboxData = current.parentElement.parentElement.querySelectorAll('.form-checkbox-main .form-check'),
checkboxValue = [];
checkboxData.forEach(current => {
(current.firstElementChild.checked == true ? checkboxValue.push(current.firstElementChild.value) : '')
});
form.append(current.innerHTML, checkboxValue);
}
}
});
if (customer_data.length != 0) {
form.append('Customer first name', customer_data[0].firstName);
form.append('Customer last name', customer_data[0].lastName);
form.append('Customer email', customer_data[0].email);
}
if (fileSizeCount == 0) {
fetch(`${Domain}sendMail?shop=${Shopify.shop}`, {
method: "POST",
headers: {
'Accept': 'application/json'
},
body: form
})
.then(res => res.json())
.then(response => {
if (response.success == 1) {
formDataSubmit.querySelector('button[type="submit"]').innerHTML = loginButtonText;
formDataSubmit.querySelector('button[type="submit"]').removeAttribute('disabled');
formDataSubmit.reset();
document.querySelector('.modal-dialog.modal-confirm').style.display = 'block';
document.querySelector('.back-shadow').style.display = 'block';
bodyTag.classList.add('mag-overflow');
} else if (response.success == 0) {
document.querySelector('.mag-toast').classList.add('active');
setTimeout(() => {
document.querySelector('.mag-toast').classList.remove('active');
}, 3000);
} else {
formDataSubmit.querySelector('button[type="submit"]').innerHTML = loginButtonText;
formDataSubmit.reset();
}
})
} else {
formDataSubmit.querySelector('button[type="submit"]').innerHTML = loginButtonText;
}
});
}
})
});
} else if (formStatus == '1') {
if (!settings || !settings.schedule_start_time || !settings.schedule_end_time) {
forms.forEach(curr => {
renderPage(curr, currentPageIndex);
});
} else {
const now = new Date();
const startTime = new Date(settings.schedule_start_time);
const endTime = new Date(settings.schedule_end_time);
if (now < startTime) {
let magMessageAppend = `
${settings.before_start_date_msg !== null && settings.before_start_date_msg !== '' ? settings.before_start_date_msg : "Before start date message"}
`;
document.querySelector(`.mag-form[data-token="${formsData.form_id}"]`).innerHTML = magMessageAppend;
} else if (now > endTime) {
let magMessageAppend = `
${settings.after_end_date_msg !== null && settings.after_end_date_msg !== '' ? settings.after_end_date_msg : "After end date message"}
`;
document.querySelector(`.mag-form[data-token="${formsData.form_id}"]`).innerHTML = magMessageAppend;
} else {
forms.forEach(curr => {
renderPage(curr, currentPageIndex);
});
}
}
}
}
const renderPage = (curr, pageIndex) => {
const divElement1 = document.createElement('div');
divElement1.setAttribute('class', 'mag-frame-content');
if (appearance.appearanceLayout === 3) {
divElement1.classList.add('mag-inner-popup', 'mag-popup-frontend');
}
else if (appearance.appearanceLayout === 2) {
divElement1.classList.add('mag-inner-popup', 'mag-float-frontend');
}
const divElement2 = document.createElement('div');
divElement2.setAttribute('class', `${handleLayoutAppearanceClassAppend()} ${handleAppearanceImageClassAppend()}`);
divElement2.style.maxWidth = appearance.FormWidth + 'px';
if (appearance.backgroundImage) {
const imagePattern = /^[0-9]+\.[A-Za-z0-9]+T[0-9]+Z\.(png|jpg|jpeg|gif)$/;
const backgroundImageUrl = appearance?.backgroundImage && imagePattern.test(appearance?.backgroundImage)
? `https://formbuilder.myappgurus.com/assets/${subdomain}/admin_panel_images/${appearance.backgroundImage}`
: `https://formbuilder.myappgurus.com/assets/Form_Builder___MyAppGurus/admin_panel_images/${appearance?.backgroundImage}`;
divElement2.style.backgroundImage = `url(${backgroundImageUrl})`;
divElement2.style.backgroundSize = 'cover';
divElement2.style.backgroundRepeat = 'no-repeat';
divElement2.style.backgroundPosition = `center ${appearance.backgroundImageAlignment}`;
}
const divElement3 = document.createElement('div');
divElement3.setAttribute('class', `mag-form-app ${handleFontSizeChanges()}`);
const divElement4 = document.createElement('div');
divElement4.setAttribute('class', `mag-form-builder-form `);
const divForImage = document.createElement('div');
divForImage.setAttribute('class', 'mag-Form-with-Image');
const imgTag = document.createElement('img');
const imageUrl = appearance?.ImageForForm && /^[0-9]+\.[A-Za-z0-9]+T[0-9]+Z\.(png|jpg|jpeg|gif)$/.test(appearance?.ImageForForm)
? `https://formbuilder.myappgurus.com/assets/${subdomain}/admin_panel_images/${appearance.ImageForForm}`
: `https://formbuilder.myappgurus.com/assets/Form_Builder___MyAppGurus/admin_panel_images/${appearance?.ImageForForm}`;
imgTag.setAttribute('src', imageUrl);
divForImage.appendChild(imgTag);
if (appearance.ImageForForm) {
divElement2.appendChild(divForImage);
}
const form = document.createElement('form');
form.setAttribute('class', 'mag-element-form');
if (data.header.showHeader) {
const header = document.createElement('div');
header.className = 'mag-form-builder-header';
header.style.textAlign = data.header.alignment;
const headerLabel = document.createElement('h1');
headerLabel.textContent = data.header.label;
header.appendChild(headerLabel);
if (data.header.description) {
const headerDescription = document.createElement('p');
headerDescription.innerHTML = data.header.description;
header.appendChild(headerDescription);
}
divElement3.appendChild(header);
}
renderProgressBar(divElement3, pageIndex);
var pageContainer = getElements(pageIndex);
form.appendChild(pageContainer);
divElement4.appendChild(form);
divElement3.appendChild(divElement4);
divElement2.appendChild(divElement3);
divElement1.appendChild(divElement2);
if (settings.LoginRequired === true) {
const mainDiv = document.createElement('div');
mainDiv.setAttribute('class', 'mag-form-container-overlayboxs');
const loginMessageDiv = document.createElement('div');
loginMessageDiv.classList.add('mag-form-overlay-box');
loginMessageDiv.innerHTML = 'Please login to continue';
mainDiv.appendChild(loginMessageDiv)
divElement1.appendChild(mainDiv);
}
if (appearance.appearanceLayout === 3) {
divElement3.insertAdjacentHTML('afterbegin', ``)
document.body.insertAdjacentHTML('afterbegin', ``);
divElement1.insertAdjacentHTML('beforeend', ``);
curr.innerHTML = '';
curr.appendChild(divElement1);
document.body.insertAdjacentElement('afterbegin', curr);
if (appearance.TriggerActions.afterScrolling === true) {
divElement1.classList.add('hide-form');
window.addEventListener('scroll', checkScrollPosition);
}
if (appearance.TriggerActions.onTimer === true) {
divElement1.classList.add('hide-form');
window.addEventListener('load', () => {
setTimeout(() => {
document.querySelector('.mag-frame-content').classList.remove('hide-form');
document.body.setAttribute('class', 'mag-popup-open');
}, (parseInt(appearance.AppearOnTimer) * 1000));
});
}
if (appearance.TriggerActions.showWhenVisitorsLeavePage === true) {
divElement1.classList.add('hide-form');
window.addEventListener('beforeunload', () => {
document.querySelector('.mag-frame-content').classList.remove('hide-form');
document.body.setAttribute('class', 'mag-popup-open');
});
}
else if (appearance.TriggerActions.afterScrolling === false && appearance.TriggerActions.onTimer === false && appearance.TriggerActions.showWhenVisitorsLeavePage === false) {
document.querySelector('.mag-frame-content').classList.remove('hide-form');
document.body.setAttribute('class', 'mag-popup-open');
}
}
else if (appearance.appearanceLayout === 2) {
divElement3.insertAdjacentHTML('afterbegin', ``)
document.body.insertAdjacentHTML('afterbegin', ``);
divElement1.insertAdjacentHTML('beforeend', ``);
curr.innerHTML = '';
curr.appendChild(divElement1);
document.body.insertAdjacentElement('afterbegin', curr);
}
else {
curr.innerHTML = '';
curr.appendChild(divElement1);
}
const formOpen = document.querySelector('.mag-form-floating-button');
if (formOpen) {
formOpen.addEventListener('click', () => {
document.querySelector('.mag-frame-content').classList.toggle('hide-form');
});
}
if (document.querySelector('.mag-form-cancel-icon')) {
var cancelIcon = document.querySelector('.mag-form-cancel-icon');
cancelIcon.addEventListener('click', () => {
document.querySelector('.mag-frame-content').classList.add('hide-form');
document.body.classList.remove('mag-popup-open');
})
}
renderPaginationControls(form, pageIndex);
// form.addEventListener('submit', handleSubmit.bind(this));
if (reCaptcha?.recaptcha_status == '1' && myappgurussettings?.recaptcha_type == 'v2') {
grecaptcha.enterprise.render(form.querySelector('#html_element'), {
'sitekey': myappgurussettings?.recaptcha_site_key,
'callback': correctCaptcha,
});
}
if (handleAppearanceStyleClassAppend(2) == 'mag-material-filled-input' || handleAppearanceStyleClassAppend(2) == 'mag-material-outlined-input') {
handleInputFocusBlur();
}
}
const renderProgressBar = (container, pageIndex) => {
if (data.formElements.length <= 1) {
return;
}
const progressBarContainer = document.createElement('div');
progressBarContainer.className = 'mag-FormBuilder-process';
const progressBarInner = document.createElement('div');
progressBarInner.className = 'mag-FormBuilder-material_filled';
const stepContainer = document.createElement('nav');
stepContainer.className = 'mag-FormBuilder-all-steps';
data.formElements.forEach((_, index) => {
const stepElement = document.createElement('div');
stepElement.className = `mag-FormBuilder-step ${index < pageIndex ? 'mag-FormBuilder-line-completed' : ''}`;
stepElement.setAttribute('data-element-id', `group-${index + 1}`);
stepElement.setAttribute('data-step', index);
const stepContent = document.createElement('div');
stepContent.className = 'mag-FormBuilder-step-content';
const stepNumber = document.createElement('p');
stepNumber.className = 'mag-FormBuilder-step-number';
const checkmarkSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
checkmarkSvg.setAttribute('class', 'mag-FormBuilder-checkmark-svg');
checkmarkSvg.setAttribute('width', '52');
checkmarkSvg.setAttribute('height', '52');
checkmarkSvg.setAttribute('viewBox', '0 0 52 52');
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute('class', 'mag-FormBuilder-checkmark-circle');
circle.setAttribute('cx', '26');
circle.setAttribute('cy', '26');
circle.setAttribute('r', '25');
circle.setAttribute('fill', 'none');
checkmarkSvg.appendChild(circle);
const checkPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
checkPath.setAttribute('class', 'mag-FormBuilder-checkmark-check');
checkPath.setAttribute('fill', 'none');
checkPath.setAttribute('d', 'M14.1 27.2l7.1 7.2 16.7-16.8');
checkmarkSvg.appendChild(checkPath);
stepContent.appendChild(stepNumber);
stepContent.appendChild(checkmarkSvg);
const linesContainer = document.createElement('div');
linesContainer.className = 'mag-FormBuilder-lines';
const lineStart = document.createElement('div');
lineStart.className = 'mag-FormBuilder-line';
if (index === pageIndex) {
lineStart.classList.add('-start');
}
const lineBackground = document.createElement('div');
lineBackground.className = 'mag-FormBuilder-line mag-FormBuilder-line-background';
const lineProgress = document.createElement('div');
lineProgress.className = 'mag-FormBuilder-line mag-FormBuilder-line-progress';
linesContainer.appendChild(lineStart);
linesContainer.appendChild(lineBackground);
linesContainer.appendChild(lineProgress);
stepContent.appendChild(linesContainer);
stepElement.appendChild(stepContent);
stepContainer.appendChild(stepElement);
});
progressBarInner.appendChild(stepContainer);
progressBarContainer.appendChild(progressBarInner);
container.appendChild(progressBarContainer);
};
const correctCaptcha = (response) => {
let submitBtn = document.querySelector('.mag-submit-btn');
if (submitBtn) {
submitBtn.removeAttribute('disabled');
}
}
const handleLayoutAppearanceClassAppend = () => {
let classsToAppend = '';
switch (appearance.appearanceLayout) {
case 0:
classsToAppend = 'mag-form-builder-default-appearance';
break;
case 1:
classsToAppend = 'mag-form-builder-Boxed-appearance';
break;
case 2:
classsToAppend = 'mag-form-builder-float-appearance';
break;
case 3:
classsToAppend = 'mag-form-builder-popup-appearance';
break;
default:
classsToAppend = 'mag-form-builder-default-appearance';
break;
}
return classsToAppend;
}
const handleFontSizeChanges = () => {
let fontSize = appearance?.FontSize || "Medium";
switch (fontSize) {
case 'Small':
return 'mag-small-font-size';
case 'Medium':
return 'mag-medium-font-size';
case 'Large':
return 'mag-large-font-size';
default:
return 'mag-medium-font-size';
}
}
const handleAppearanceImageClassAppend = () => {
let classsToAppend = '';
let ratio;
let imagePosition = appearance?.FormWithImage || 'no_image';
if (appearance?.ImageForForm !== null && appearance?.ImageForForm !== '') {
switch (imagePosition) {
case 'top':
classsToAppend = 'mag-top-Form-with-Image';
break;
case 'left':
ratio = parseInt(appearance?.RatioBetweenImageAndForm) || '50';
classsToAppend = `mag-left-Form-with-Image mag-image-ratio-${ratio}`;
break;
case 'right':
ratio = parseInt(appearance?.RatioBetweenImageAndForm) || '50';
classsToAppend = `mag-right-Form-with-Image mag-image-ratio-${ratio}`;
break;
default:
classsToAppend = '';
break;
}
}
return classsToAppend;
}
const handleAppearanceStyleClassAppend = (divType) => {
let classsToAppend = '';
if (appearance.FormStyleClass.trim().includes('mag-material-filled-input') && divType == 2) {
classsToAppend = 'mag-material-filled-input';
}
else if (appearance.FormStyleClass.trim().includes('mag-material-outlined-input') && divType == 2) {
classsToAppend = 'mag-material-outlined-input';
}
else if (appearance.FormStyleClass.trim().includes('mag-defult-element')) {
if (divType == 1) {
classsToAppend = 'mag-defult-element';
}
else if (divType == 2 && appearance.FormStyleClass.trim().includes('mag-classic-input-radius')) {
classsToAppend = 'mag-classic-input-radius';
}
else if (divType == 2 && appearance.FormStyleClass.trim().includes('mag-classic-input')) {
classsToAppend = 'mag-classic-input';
}
else if (divType == 2 && appearance.FormStyleClass.trim().includes('mag-flat-input-radius')) {
classsToAppend = 'mag-flat-input-radius';
}
else if (divType == 2 && appearance.FormStyleClass.trim().includes('mag-flat-input')) {
classsToAppend = 'mag-flat-input';
}
else if (divType == 2 && appearance.FormStyleClass.trim().includes('mag-line-input')) {
classsToAppend = 'mag-line-input';
}
else if (divType == 3 && appearance.FormStyleClass.trim().includes('mag-line-less-radius')) {
classsToAppend = 'mag-line-less-radius';
}
else if (divType == 3 && appearance.FormStyleClass.trim().includes('mag-line-round-radius')) {
classsToAppend = 'mag-line-round-radius';
}
else {
classsToAppend = '';
}
}
return classsToAppend;
}
const createLabel = (pageElement) => {
const labelTag = document.createElement('label');
{ pageElement.contentValue.required === true ? labelTag.innerHTML = `${pageElement.contentValue.label}*` : labelTag.innerHTML = `${pageElement.contentValue.label}` }
return labelTag;
}
const createDropDown = (pageElement, name, pageIndex) => {
if (pageElement.elementType === 'CountryInput') {
const selectOption = document.createElement('select');
if (pageElement.contentValue.required) {
selectOption.setAttribute('required', true);
}
selectOption.setAttribute('class', `mag-form-select mag-dropdown`);
selectOption.setAttribute('name', name);
selectOption.setAttribute('data-label', name);
checkDependentElement(pageElement, selectOption);
const placeholder = pageElement.contentValue.placeholder || 'Choose a country';
const placeholderOption = document.createElement('option');
placeholderOption.setAttribute('value', '');
placeholderOption.textContent = placeholder;
placeholderOption.disabled = true;
placeholderOption.selected = true;
selectOption.appendChild(placeholderOption);
countries.forEach((Options, index) => {
const option = document.createElement('option');
option.setAttribute('value', Options.value);
option.setAttribute('key', index);
option.textContent = Options.label;
selectOption.appendChild(option);
});
return selectOption;
}
else {
const selectOption = document.createElement('select');
selectOption.setAttribute('name', name);
selectOption.setAttribute('data-label', name);
checkDependentElement(pageElement, selectOption);
if (pageElement.contentValue.required) {
selectOption.setAttribute('required', true);
}
selectOption.setAttribute('class', `mag-form-select`);
const placeholderOption = document.createElement('option');
placeholderOption.setAttribute('value', '');
placeholderOption.setAttribute('disabled', true);
placeholderOption.setAttribute('selected', true);
placeholderOption.textContent = pageElement.contentValue.placeholder || 'Select Option';
selectOption.appendChild(placeholderOption);
pageElement.contentValue.options.forEach((Options) => {
const option = document.createElement('option');
option.setAttribute('value', Options.value);
option.setAttribute('class', 'mag-form-select');
option.textContent = Options.label;
selectOption.appendChild(option);
});
return selectOption;
}
}
const checkDependentElement = (pageElement, currField) => {
if (pageElement.contentValue.dependedElement && pageElement.contentValue.dependedElement !== '') {
observeElementAddition(pageElement.contentValue.dependedElement, pageElement.contentValue.dependedValue, (element, elementCheckbox) => {
if (element) {
if (currField.closest('div')) {
element.forEach(curr => {
if (elementCheckbox) {
if (curr.value == pageElement.contentValue.dependedValue && elementCheckbox.checked) {
currField.closest('div').style.display = 'block';
if (pageElement.contentValue.required === true) {
currField.setAttribute('required', 'required');
} else {
currField.removeAttribute('required');
}
} else {
currField.closest('div').style.display = 'none';
currField?.removeAttribute('required');
currField?.setAttribute('value', '');
}
} else {
if (curr.value == pageElement.contentValue.dependedValue) {
currField.closest('div').style.display = 'block';
if (pageElement.contentValue.required === true) {
currField.setAttribute('required', 'required');
} else {
currField.removeAttribute('required');
}
} else {
currField.closest('div').style.display = 'none';
currField?.removeAttribute('required');
currField?.setAttribute('value', '');
}
}
curr.addEventListener('change', () => {
if (elementCheckbox) {
if (curr.value == pageElement.contentValue.dependedValue) {
if (elementCheckbox.checked) {
currField.closest('div').style.display = 'block';
if (pageElement.contentValue.required === true) {
currField.setAttribute('required', 'required');
} else {
currField.removeAttribute('required');
}
} else {
currField.closest('div').style.display = 'none';
currField?.removeAttribute('required');
currField?.setAttribute('value', '');
}
}
} else {
if (curr.value == pageElement.contentValue.dependedValue) {
currField.closest('div').style.display = 'block';
if (pageElement.contentValue.required === true) {
currField.setAttribute('required', 'required');
} else {
currField.removeAttribute('required');
}
} else {
currField.closest('div').style.display = 'none';
currField?.removeAttribute('required');
currField?.setAttribute('value', '');
}
}
});
});
}
}
});
}
}
const createTextarea = (pageElement, pageIndex) => {
const textarea = document.createElement('textarea');
textarea.setAttribute('rows', pageElement.contentValue.inputRows);
textarea.setAttribute('data-label', pageElement.contentValue.label);
textarea.setAttribute('cols', pageElement.contentValue.inputCols);
textarea.setAttribute('placeholder', pageElement.contentValue.placeholder != null ? pageElement.contentValue.placeholder : '');
textarea.setAttribute('data-pageid', pageIndex + 1);
textarea.setAttribute('data-fieldid', pageElement.fieldId);
textarea.setAttribute('size', pageElement.contentValue.sizeInPercentage);
textarea.setAttribute('class', `mag-form-control`);
if (pageElement.contentValue.required) {
textarea.required = true;
}
textarea.setAttribute('name', pageElement.contentValue.label ? pageElement.contentValue.label : '');
checkDependentElement(pageElement, textarea);
return textarea;
}
const createMultilineInput = (pageElement) => {
const multiline = document.createElement('div');
multiline.setAttribute('class', `mag-form-element mag-form-floating ${handleAppearanceStyleClassAppend(2)}`);
pageElement.contentValue.lines.forEach((line, index) => {
const multilineEle = document.createElement('input');
multilineEle.setAttribute('type', 'text');
multilineEle.setAttribute('class', `mag-form-control mag-form-multilineele-text`);
multilineEle.setAttribute('placeholder', line.placeholder || '');
multilineEle.style.width = pageElement.contentValue.sizeInPercentage ? `${pageElement.contentValue.sizeInPercentage}%` : '100%';
if (line.value) {
multilineEle.value = line.value;
}
multiline.appendChild(multilineEle);
});
checkDependentElement(pageElement, multiline);
return multiline;
}
const createMultiColumnInput = (pageElement, pageIndex) => {
const multiColumn = document.createElement('div');
multiColumn.setAttribute('class', `mag-form-multi-column-raw`);
multiColumn.setAttribute('data-pageid', pageIndex + 1);
multiColumn.setAttribute('data-fieldid', pageElement.fieldId);
if (pageElement.contentValue.required) {
multiColumn.setAttribute('required', 'true');
}
pageElement.contentValue.columns.forEach((column, index) => {
const columnWrapper = document.createElement('div');
columnWrapper.className = 'mag-form-column';
const multiColumnEle = document.createElement('input');
multiColumnEle.setAttribute('type', 'text');
multiColumnEle.setAttribute('class', `mag-form-control mag-form-multicolumnele-text`);
multiColumnEle.setAttribute('placeholder', column.placeholder || '');
multiColumnEle.style.width = pageElement.contentValue.sizeInPercentage ? `${pageElement.contentValue.sizeInPercentage}%` : '100%';
if (column.value) {
multiColumnEle.value = column.value;
}
columnWrapper.appendChild(multiColumnEle);
multiColumn.appendChild(columnWrapper);
});
checkDependentElement(pageElement, multiColumn);
return multiColumn;
}
const createHeaderInput = (pageElement) => {
const header = document.createElement('h2');
header.textContent = pageElement.contentValue.headerText;
header.classList.add('mag-text-header');
header.classList.add(`mag-align-${pageElement.contentValue.alignment}`);
return header;
}
const createParagraphInput = (pageElement) => {
const paragraph = document.createElement('p');
paragraph.innerHTML = pageElement.contentValue.paragraphText;
paragraph.classList.add('mag-text-paragraph');
return paragraph;
}
const createImages = (pageElement, name) => {
const wrapperDiv = document.createElement('div');
wrapperDiv.setAttribute('aria-label', pageElement.contentValue.description);
wrapperDiv.className = 'mag-form-element-image-options';
pageElement.contentValue.options.forEach((option, optIndex) => {
const optionDiv = document.createElement('div');
optionDiv.className = 'mag-image-option';
const innerDiv = document.createElement('div');
innerDiv.className = 'mag-form-element-image-option-inner';
if (option.imageFile && typeof option.imageFile === 'string' && option.imageFile.trim() !== '') {
const img = document.createElement('img');
const imageurl = `https://formbuilder.myappgurus.com/assets/${subdomain}/admin_panel_images/${option.imageFile}`;
img.setAttribute('src', imageurl);
img.setAttribute('alt', option.label);
innerDiv.appendChild(img);
} else {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
svg.setAttribute("viewBox", "0 0 16 16");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("fill", "#5C5F62");
path.setAttribute("d", "M.002 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-12a2 2 0 0 1-2-2zm1 9v1a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71l-2.66-1.772a.5.5 0 0 0-.63.062zm5-6.5a1.5 1.5 0 1 0-3 0a1.5 1.5 0 0 0 3 0");
svg.appendChild(path);
innerDiv.appendChild(svg);
}
optionDiv.appendChild(innerDiv);
const inputDiv = document.createElement('div');
inputDiv.className = 'mag-form-element-image-option-inner-input';
const input = document.createElement('input');
input.setAttribute('type', pageElement.contentValue.multipleSelection ? 'checkbox' : 'radio');
input.setAttribute('name', name);
input.setAttribute('value', option.value);
input.setAttribute('aria-label', pageElement.contentValue.description);
if (pageElement.contentValue.required) {
input.required = true;
input.addEventListener('invalid', (event) => {
input.setCustomValidity(pageElement.contentValue.requiredMessage || 'This field is required');
});
input.addEventListener('input', () => {
input.setCustomValidity('');
});
}
input.addEventListener('change', (event) => {
const selectedFile = event.target.files ? event.target.files[0] : null;
if (selectedFile) {
if (pageElement.contentValue.maxFileSize && selectedFile.size > pageElement.contentValue.maxFileSize) {
input.setCustomValidity(pageElement.contentValue.FileSizeLimitMessage || 'File size exceeds the limit');
return;
}
if (pageElement.contentValue.allowedFileTypes && !pageElement.contentValue.allowedFileTypes.includes(selectedFile.type)) {
input.setCustomValidity(pageElement.contentValue.FileTypeMessage || 'Invalid file type');
return;
}
input.setCustomValidity('');
}
});
optionDiv.addEventListener('click', () => {
input.click();
});
const label = document.createElement('label');
label.textContent = option.label;
inputDiv.appendChild(input);
inputDiv.appendChild(label);
optionDiv.appendChild(inputDiv);
wrapperDiv.appendChild(optionDiv);
});
return wrapperDiv;
};
const createProducts = (pageElement, name) => {
const wrapperDiv = document.createElement('div');
wrapperDiv.setAttribute('aria-label', pageElement.contentValue.description);
wrapperDiv.className = 'mag-form-element-image-options';
pageElement.contentValue.options?.forEach((option, optIndex) => {
const optionDiv = document.createElement('div');
optionDiv.className = 'mag-image-option';
const innerDiv = document.createElement('div');
innerDiv.className = 'mag-form-element-image-option-inner';
if (option.imageFile && typeof option.imageFile === 'string' && option.imageFile.trim() !== '') {
const img = document.createElement('img');
const imageurl = option.imageFile;
img.setAttribute('src', imageurl);
img.setAttribute('alt', option.label);
innerDiv.appendChild(img);
} else {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
svg.setAttribute("viewBox", "0 0 16 16");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("fill", "#5C5F62");
path.setAttribute("d", "M.002 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-12a2 2 0 0 1-2-2zm1 9v1a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9.5l-3.777-1.947a.5.5 0 0 0-.577.093l-3.71 3.71l-2.66-1.772a.5.5 0 0 0-.63.062zm5-6.5a1.5 1.5 0 1 0-3 0a1.5 1.5 0 0 0 3 0");
svg.appendChild(path);
innerDiv.appendChild(svg);
}
optionDiv.appendChild(innerDiv);
const inputDiv = document.createElement('div');
inputDiv.className = 'mag-form-element-image-option-inner-input';
const input = document.createElement('input');
input.setAttribute('type', pageElement.contentValue.multipleSelection ? 'checkbox' : 'radio');
input.setAttribute('name', name);
input.setAttribute('value', option.value);
input.setAttribute('aria-label', pageElement.contentValue.description);
if (pageElement.contentValue.required) {
input.required = true;
input.addEventListener('invalid', (event) => {
input.setCustomValidity(pageElement.contentValue.requiredMessage || 'This field is required');
});
input.addEventListener('input', () => {
input.setCustomValidity('');
});
}
input.addEventListener('change', (event) => {
const selectedFile = event.target.files ? event.target.files[0] : null;
if (selectedFile) {
if (pageElement.contentValue.maxFileSize && selectedFile.size > pageElement.contentValue.maxFileSize) {
input.setCustomValidity(pageElement.contentValue.FileSizeLimitMessage || 'File size exceeds the limit');
return;
}
if (pageElement.contentValue.allowedFileTypes && !pageElement.contentValue.allowedFileTypes.includes(selectedFile.type)) {
input.setCustomValidity(pageElement.contentValue.FileTypeMessage || 'Invalid file type');
return;
}
input.setCustomValidity('');
}
});
optionDiv.addEventListener('click', () => {
input.click();
});
const label = document.createElement('label');
label.textContent = option.label;
inputDiv.appendChild(input);
inputDiv.appendChild(label);
optionDiv.appendChild(inputDiv);
wrapperDiv.appendChild(optionDiv);
});
return wrapperDiv;
};
const createQuantityInputElement = (pageElement, name, pageIndex) => {
const inputWrapper = document.createElement('div');
inputWrapper.className = 'mag-form-input';
const minusButton = document.createElement('span');
minusButton.className = 'mag-quantity-button mag-minus-button';
minusButton.innerHTML = ``;
minusButton.onclick = () => handleQuantityClick(-1);
inputWrapper.appendChild(minusButton);
const input = document.createElement('input');
input.type = 'number';
input.className = `mag-quantity-input`;
input.id = `quantity-quantity`;
input.name = name;
input.min = '0';
input.step = '1';
input.value = 0;
input.style.width = '100%';
input.setAttribute('data-pageid', pageIndex + 1);
input.setAttribute('data-fieldid', pageElement.fieldId);
if (pageElement.contentValue.required) {
input.required = true;
}
let maxQuantity = null;
if (pageElement.contentValue.maxLimitChecked && pageElement.contentValue.maxQuantity) {
maxQuantity = parseInt(pageElement.contentValue.maxQuantity, 10);
input.max = maxQuantity;
}
input.oninput = handleQuantityChange;
inputWrapper.appendChild(input);
const addButton = document.createElement('span');
addButton.className = 'mag-quantity-button mag-add-button';
addButton.innerHTML = ``;
addButton.onclick = () => handleQuantityClick(1);
inputWrapper.appendChild(addButton);
const errorMessage = document.createElement('div');
errorMessage.className = 'mag-error-message';
errorMessage.style.color = 'red';
errorMessage.style.display = 'none';
errorMessage.textContent = `The maximum quantity allowed is ${maxQuantity}.`;
inputWrapper.insertAdjacentElement('afterend', errorMessage);
function handleQuantityChange(event) {
const value = Math.max(0, parseInt(event.target.value, 10) || 0);
if (maxQuantity !== null && value > maxQuantity) {
event.target.value = maxQuantity;
showError(true);
} else {
event.target.value = value;
showError(false);
}
}
function handleQuantityClick(change) {
const currentValue = parseInt(input.value, 10) || 0;
const newValue = currentValue + change;
if (newValue >= 0 && (maxQuantity === null || newValue <= maxQuantity)) {
input.value = newValue;
showError(false);
} else if (maxQuantity !== null && newValue > maxQuantity) {
showError(true);
}
}
function showError(show) {
if (show) {
errorMessage.style.display = 'block';
} else {
errorMessage.style.display = 'none';
}
}
return inputWrapper;
}
const handleflotingFormPosition = () => {
let classsToAppend = '';
let positionFloatingIcon = appearance?.positionFloatingIcon || '';
if ((appearance.appearanceLayout === 2 || appearance.appearanceLayout === 3)) {
switch (positionFloatingIcon) {
case "topRight":
classsToAppend = 'mag-float-top-right-btn';
break;
case "halfTopRight":
classsToAppend = 'mag-float-half-top-right-btn';
break;
case "centerRight":
classsToAppend = 'mag-float-center-right-btn';
break;
case "halfBottomRight":
classsToAppend = 'mag-float-half-bottom-right-btn';
break;
case "bottomRight":
classsToAppend = 'mag-float-bottom-right-btn';
break;
case "halfBottomLeft":
classsToAppend = 'mag-float-half-bottom-left-btn';
break;
case "bottomLeft":
classsToAppend = 'mag-float-bottom-left-btn';
break;
case "centerLeft":
classsToAppend = 'mag-float-center-left-btn';
break;
case "topLeft":
classsToAppend = 'mag-float-top-left-btn';
break;
case "halfTopLeft":
classsToAppend = 'mag-float-half-top-left-btn';
break;
default:
classsToAppend = '';
break;
}
}
return classsToAppend;
}
const createRangeBar = (pageElement, name, minRange, maxRange, defaultRange) => {
const rangeBar = document.createElement('input');
rangeBar.setAttribute('type', jsonToHtml[pageElement.elementType]);
if (pageElement.contentValue.required) {
rangeBar.setAttribute('required', true);
}
rangeBar.setAttribute('class', 'mag-material-filled-input');
rangeBar.setAttribute('name', name);
rangeBar.setAttribute('min', minRange);
rangeBar.setAttribute('max', maxRange);
rangeBar.setAttribute('value', defaultRange);
return rangeBar;
}
let confirmPasswordInput = null;
let passwordInputCheck = null;
const handleValidationMessages = (input, pageElement) => {
let validationMessage = '';
var passwordCriteria = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).+$/;
var passwordInput = null;
const setValidationMessage = () => {
if (input.validity.valueMissing) {
validationMessage = 'This field is required' || settings.RequiredMessage;
} else if (input.validity.patternMismatch) {
validationMessage = 'Field value does not match the given pattern' || settings.InvalidMessage;
} else if (input.validity.typeMismatch && input.type === 'email') {
validationMessage = 'Please enter a valid email' || settings.InvalidEmailMessage;
} else if (input.validity.typeMismatch && input.type === 'url') {
validationMessage = 'Please enter a valid url' || settings.InvalidUrlMessage;
} else if (input.validity.typeMismatch && input.type === 'number') {
validationMessage = 'Please enter a number' || settings.InvalidNumberMessage;
} else if (input.type === 'password' && input.value) {
passwordInput = input.value.trim();
if (!passwordCriteria.test(passwordInput)) {
validationMessage = settings.InvalidPasswordMessage || 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.';
}
} else {
validationMessage = '';
}
if (input.name === 'password') {
passwordInputCheck = input;
}
if (input.name === 'confirmpassword') {
confirmPasswordInput = input;
}
if (passwordInputCheck && confirmPasswordInput) {
if (confirmPasswordInput.value != passwordInputCheck.value) {
validationMessage = 'Passwords do not match' || settings.ConfirmPasswordMessage
}
}
input.setCustomValidity(validationMessage);
return validationMessage;
};
const initialMessage = setValidationMessage();
input.addEventListener('invalid', setValidationMessage);
input.addEventListener('input', () => {
input.setCustomValidity('');
validationMessage = '';
});
return initialMessage;
};
const observeElementAddition = (dependedElementName, dependedElementValue, callback) => {
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
const dependentElement = document.querySelectorAll(`[data-label="${dependedElementName}"]`),
dependedElementCheckbox = document.querySelector(`input[type="checkbox"][name="${dependedElementName}"][value="${dependedElementValue}"]`);
if (dependentElement) {
callback(dependentElement, dependedElementCheckbox);
observer.disconnect();
}
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
}
const createInputElement = (pageElement, name, pageIndex) => {
if (pageElement.elementType === 'AcceptTermsInput') {
const input = document.createElement('input')
input.setAttribute('type', jsonToHtml[pageElement.elementType]);
if (pageElement.contentValue.required) {
input.setAttribute('required', true);
}
input.setAttribute('name', name);
input.setAttribute('data-label', pageElement.contentValue.label);
input.setAttribute('class', `mag-material-filled-input`);
pageElement.contentValue.defaultChecked === true ? input.setAttribute('checked', true) : '';
handleValidationMessages(input, pageElement);
const label = document.createElement('div');
label.setAttribute('class', 'mag-form-label');
label.setAttribute('data-label', pageElement.contentValue.label);
label.innerText = pageElement.contentValue.label;
if (pageElement.contentValue.required) {
const asterisk = document.createElement('span');
asterisk.innerText = ' *';
asterisk.classList.add('mag-form-text-require');
label.appendChild(asterisk);
}
const divWrapper = document.createElement('div');
divWrapper.setAttribute('class', `mag-form-terms-label ${handleAppearanceStyleClassAppend(3)}`);
divWrapper.appendChild(input);
divWrapper.appendChild(label);
checkDependentElement(pageElement, input);
return divWrapper;
}
else if (pageElement.elementType === 'CheckboxInput') {
const mainDiv = document.createElement('div');
let checkboxes = [];
pageElement.contentValue.options.forEach((option, index) => {
const div = document.createElement('div');
const input = document.createElement('input')
input.setAttribute('type', jsonToHtml[pageElement.elementType]);
input.setAttribute('name', name);
input.setAttribute('value', option.value);
input.setAttribute('id', `${index}_${name}`);
if (option.defaultChecked === true) {
input.checked = true;
}
pageElement.contentValue.defaultChecked === true ? input.setAttribute('checked', true) : '';
input.setAttribute('class', `mag-form-control`);
checkboxes.push(input);
const label = document.createElement('label');
label.setAttribute('for', `${index}_${name}`);
label.textContent = option.label;
div.setAttribute('class', `mag-form-control`);
div.appendChild(input);
div.appendChild(label);
mainDiv.appendChild(div);
handleValidationMessages(input, pageElement);
});
checkboxes.forEach((checkbox) => {
checkbox.addEventListener('change', () => {
const isAnyChecked = checkboxes.some((cb) => cb.checked);
checkboxes.forEach((cb) => {
if (pageElement.contentValue.required) {
if (isAnyChecked) {
cb.removeAttribute('required');
} else {
cb.setAttribute('required', 'true');
}
}
});
});
});
const isAnyCheckedInitially = checkboxes.some((cb) => cb.checked);
checkboxes.forEach((cb) => {
if (pageElement.contentValue.required) {
if (isAnyCheckedInitially) {
cb.removeAttribute('required');
} else {
cb.setAttribute('required', 'true');
}
}
});
return mainDiv;
}
else if (pageElement.elementType === 'ButtonInput') {
const mainDiv = document.createElement('div');
mainDiv.setAttribute('class', 'mag-form-button-group mag-layout-col-1');
pageElement.contentValue.options.forEach((buttonOption) => {
const button = document.createElement('button');
button.setAttribute('type', 'button');
button.setAttribute('class', `${handleAppearanceStyleClassAppend(2)}`);
button.setAttribute('value', buttonOption.value || '');
button.setAttribute('name', name);
button.setAttribute('aria-label', buttonOption.ariaLabel || '');
button.textContent = buttonOption.label;
button.addEventListener('click', () => {
mainDiv.querySelectorAll('button').forEach(btn => btn.classList.remove('selected'));
button.classList.add('selected');
});
mainDiv.appendChild(button);
});
return mainDiv;
}
else if (pageElement.elementType === 'RadioInput') {
const mainDiv = document.createElement('div');
pageElement.contentValue.options.forEach((option, index) => {
const div = document.createElement('div');
div.className = 'mag-form-option-radio';
const input = document.createElement('input')
input.setAttribute('type', jsonToHtml[pageElement.elementType]);
if (pageElement.contentValue.required) {
input.setAttribute('required', 'true');
}
input.setAttribute('name', name);
input.setAttribute('value', option.value);
input.setAttribute('id', `${index}_${name}`);
if (option.defaultChecked) {
input.setAttribute('checked', 'true');
}
const label = document.createElement('label');
label.setAttribute('for', `${index}_${name}`);
label.textContent = option.label;
div.appendChild(input);
div.appendChild(label);
mainDiv.appendChild(div);
handleValidationMessages(input, pageElement);
});
return mainDiv;
}
else {
const input = document.createElement('input');
input.setAttribute('type', jsonToHtml[pageElement.elementType] || 'text');
if (pageElement.contentValue.required) {
input.setAttribute('required', 'true');
}
if (pageElement.contentValue.description) {
input.setAttribute('aria-label', pageElement.contentValue.description)
}
input.setAttribute('data-pageid', pageIndex + 1);
input.setAttribute('data-fieldid', pageElement.fieldId);
if (pageElement.contentValue.placeholder) {
input.setAttribute('placeholder', pageElement.contentValue.placeholder);
}
if (pageElement.elementType === 'PasswordInput') {
if (pageElement.contentValue.minLength) {
input.setAttribute('minlength', pageElement.contentValue.minLength);
}
if (pageElement.contentValue.maxLength) {
input.setAttribute('maxlength', pageElement.contentValue.maxLength);
}
}
else if (pageElement.elementType === 'TimePickerInput') {
input.setAttribute('type', 'time');
if (pageElement.contentValue.minTime) {
input.setAttribute('min', pageElement.contentValue.minTime);
}
if (pageElement.contentValue.maxTime) {
input.setAttribute('max', pageElement.contentValue.maxTime);
}
}
else if (pageElement.elementType === 'DatePickerInput') {
input.setAttribute('type', 'date');
if (pageElement.contentValue.minDate) {
input.setAttribute('min', pageElement.contentValue.minDate);
}
if (pageElement.contentValue.maxDate) {
input.setAttribute('max', pageElement.contentValue.maxDate);
}
}
else if (pageElement.elementType === 'FileInput') {
const types = [];
if (pageElement.contentValue.fileTypes) {
pageElement.contentValue.fileTypes.forEach((fileType) => {
types.push('.' + fileType);
});
input.setAttribute('accept', types);
}
if (pageElement.contentValue.multipleFiles) {
input.setAttribute('multiple', '');
}
}
else if (pageElement.elementType === 'SignatureInput') {
const types = [];
if (pageElement.contentValue.AcceptedTypes) {
pageElement.contentValue.AcceptedTypes.forEach((fileType) => {
types.push('.' + fileType);
});
input.setAttribute('accept', types);
}
if (pageElement.contentValue.multipleFiles) {
input.setAttribute('multiple', '');
}
}
checkDependentElement(pageElement, input);
input.setAttribute('name', name);
input.setAttribute('data-label', pageElement.contentValue.label);
input.setAttribute('class', (pageElement.elementType !== ('ColorInput' || 'DatePickerInput')) ? `mag-form-control` : `mag-form-select`);
pageElement.contentValue.inputPattern ? input.setAttribute('pattern', pageElement.contentValue.inputPattern ? pageElement.contentValue.inputPattern : '') : '';
return input;
}
}
const reviewValueChange = (divElement) => {
let reviews = divElement.querySelectorAll('.bi-star-fill.mag-reviews');
if (reviews) {
reviews.forEach(curr => {
curr.addEventListener('click', () => {
let val = curr.getAttribute('star-data'),
reviewRating = divElement.querySelectorAll(`.mag-reviews`);
reviewRating.forEach((curr, index) => {
if (index < parseInt(val)) {
curr.classList.add('filled');
curr.setAttribute('fill', `${textColorRgb}`);
curr.setAttribute('stroke', 'orange');
} else {
curr.classList.remove('filled');
curr.setAttribute('fill', `${backgroundColorRgb}`);
curr.setAttribute('stroke', 'currentColor');
}
});
divElement.querySelector(`.mag-reviews`).value = val;
});
});
}
};
const checkScrollPosition = () => {
const scrollPosition = window.scrollY + window.innerHeight;
const documentHeight = document.documentElement.scrollHeight;
const scrollPercentage = (scrollPosition / documentHeight) * 100;
if (appearance.AppearAfterScrolling == 0) {
appearance.AppearAfterScrolling = 25;
}
if (scrollPercentage >= appearance.AppearAfterScrolling) {
document.querySelector('.mag-frame-content').classList.remove('hide-form');
document.body.setAttribute('class', 'mag-popup-open');
window.removeEventListener('scroll', checkScrollPosition);
}
}
const renderPaginationControls = (form, pageIndex) => {
while (form.children.length > 1) {
form.removeChild(form.lastChild);
}
const footer = document.createElement('div');
footer.className = `mag-appearance-color-customisation-buttons ${handleAppearanceStyleClassAppend(2)}`;
if (data.footer.fullWidthFooter) {
footer.classList.add('mag-fullwidth');
}
else if (data.footer.alignment) {
footer.classList.add(`mag-align-${data.footer.alignment}`);
}
if (data.footer.resetChecked) {
const resetButton = document.createElement('button');
resetButton.textContent = data.footer.reset;
resetButton.type = 'reset';
resetButton.className = 'mag-action mag-reset-btn mag-line-rounded-btn';
resetButton.onclick = () => form.reset();
footer.appendChild(resetButton);
}
if (pageIndex > 0) {
const prevButton = document.createElement('button');
prevButton.textContent = data.footer.previouse;
prevButton.type = 'button';
prevButton.className = 'mag-action mag-previous-btn mag-line-rounded-btn';
prevButton.onclick = () => handlePrevClick(form, pageIndex);
footer.appendChild(prevButton);
}
if (pageIndex < data.formElements.length - 1) {
const nextButton = document.createElement('button');
nextButton.textContent = data.footer.next;
nextButton.type = 'button';
nextButton.className = 'mag-action mag-next-btn mag-line-rounded-btn';
nextButton.addEventListener('click', async (event) => {
var hasErrors = await handleValidationAndDisplayErrors();
if (!hasErrors) {
handleNextClick(form, pageIndex, event);
}
});
footer.appendChild(nextButton);
} else {
const submitButton = document.createElement('button');
submitButton.textContent = data.footer.submit;
submitButton.addEventListener('click', async (event) => {
event.preventDefault();
var hasErrors = await handleValidationAndDisplayErrors();
if (!hasErrors) {
handleSubmitClick(form);
await handleSubmit(event, form);
}
});
submitButton.type = 'submit';
submitButton.className = 'mag-action mag-submit-btn mag-line-rounded-btn';
if (reCaptcha?.recaptcha_status == '1' && myappgurussettings?.recaptcha_type == 'v2') {
submitButton.disabled = 'true';
}
footer.appendChild(submitButton);
}
form.appendChild(footer);
const logoDiv = document.createElement('div');
logoDiv.className = 'mag-logo-image';
logoDiv.style.display = removeWatermark == '1' ? 'none' : 'block !important';
const logoWrapper = document.createElement('div');
logoWrapper.className = 'mag-logo-wrapper';
const logoLink = document.createElement('a');
logoLink.href = 'https://apps.shopify.com/form-builder-myappgurus';
logoLink.target = '_blank';
logoLink.rel = 'nofollow';
logoLink.style.color = 'blue';
logoLink.style.display = removeWatermark == '1' ? 'none' : 'inline-block !important';
logoLink.style.textDecoration = 'underline';
const logoText = document.createElement('span');
logoText.textContent = 'Powered By: MyAppGurus';
logoText.style.display = removeWatermark == '1' ? 'none' : 'inline-block !important';
logoLink.appendChild(logoText);
logoWrapper.appendChild(logoLink);
logoDiv.appendChild(logoWrapper);
footer.after(logoDiv);
}
const handlePrevClick = (form, pageIndex) => {
saveCurrentPageData(form);
changePage(form.parentNode, pageIndex - 1);
}
const handleNextClick = (form, pageIndex, event) => {
event.preventDefault();
saveCurrentPageData(form);
changePage(form.parentNode, pageIndex + 1);
}
const handleSubmitClick = (form) => {
saveCurrentPageData(form);
}
const saveCurrentPageData = (form) => {
const inputs = form.querySelectorAll('input, textarea, Button');
inputs.forEach(input => {
const key = `${input.name}`;
if (input.type === 'text' && input.classList.contains('mag-form-multilineele-text')) {
const multilineContainer = input.closest('.mag-form-element');
if (multilineContainer) {
const multilineInputs = multilineContainer.querySelectorAll('.mag-form-line input');
const values = Array.from(multilineInputs).map(input => input.value).filter(value => value);
if (values.length > 0) {
const containerLabel = multilineContainer.querySelector('.mag-form-label')?.textContent.replace('*', '').trim() || 'MultiLine';
formData[containerLabel] = values.join(' | ');
formData[key] = values.join(' | ');
}
}
} else if (input.type === 'text' && input.classList.contains('mag-form-multicolumnele-text')) {
const multicolumnContainer = input.closest('.mag-form-element');
if (multicolumnContainer) {
const multicolumnInputs = multicolumnContainer.querySelectorAll('.mag-form-column input');
const values = Array.from(multicolumnInputs).map(input => input.value).filter(value => value);
if (values.length > 0) {
const containerLabel = multicolumnContainer.querySelector('.mag-form-label')?.textContent.replace('*', '').trim() || 'MultiColumn';
formData[containerLabel] = values.join(' | ');
formData[key] = values.join(' | ');
}
}
} else if (input.type === 'file' && input.files.length > 0) {
for (let i = 0; i < input.files.length; i++) {
formData[`${key}_${i + 1}`] = input.files[i];
}
} else if (input.type === 'checkbox' && input.name !== 'acceptterms') {
if (!Array.isArray(formData[key])) {
formData[key] = [];
}
if (input.checked) {
const checkboxValue = input.value || null;
if (checkboxValue) {
formData[key].push(checkboxValue);
}
}
} else if (input.type === 'radio') {
const checkedRadio = form.querySelector(`input[name="${input.name}"]:checked`);
if (checkedRadio) {
formData[input.name] = checkedRadio.value;
}
} else if (input.name === 'acceptterms' && input.checked) {
formData[key] = input.checked ? true : false;
} else if (input.type === 'email') {
formData[key] = input.value;
formData['cust_email'] = input.value;
} else if (input.type === 'textarea') {
formData[key] = input.value;
} else if (input.classList.contains('mag-form-button-group')) {
const selectedButton = input.querySelector('.mag-form-button-group .mag-material-filled-input .selected');
formData[key] = selectedButton ? selectedButton.value : '';
}
else {
const value = input.value.trim();
if (value) {
formData[key] = value;
}
}
});
const addressFields = Array.from(form.querySelectorAll('.mag-address-element-wrapper'));
addressFields.forEach(addressField => {
let key = addressField.getAttribute('data-label');
let addressLine1 = addressField.querySelector('input[name="addressline1"]').value.trim();
let addressLine2 = addressField.querySelector('input[name="addressline2"]').value.trim();
let city = addressField.querySelector('input[name="city"]').value.trim();
let zipcode = addressField.querySelector('input[name="zipcode"]').value.trim();
let country = addressField.querySelector('select[name="country"]').value.trim();
let formattedAddress = `${addressLine1}`;
if (addressLine2) {
formattedAddress += `\n${addressLine2}`;
}
formattedAddress += `\n${city} - ${zipcode},\n${country}`;
formData[key] = formattedAddress;
});
const emailFields = Array.from(form.querySelectorAll('input[type="email"]'));
emailFields.forEach(emailField => {
if (emailField.value) {
if (!formData.emailArray) {
formData.emailArray = [];
}
formData.emailArray.push(emailField.value);
}
});
const feedback = form.querySelector('.mag-form-feedback-preview .selected');
if (feedback) {
const labelElement = form.querySelector('.mag-form-label-static-feedback').textContent.toLowerCase().replace(/\s+/g, '') || 'feedBack';
formData[labelElement] = feedback.dataset.value;
}
const selects = form.querySelectorAll('select');
if (selects) {
selects.forEach(select => {
const key = select.name;
formData[key] = select.value;
});
}
const switchInput = form.querySelector('.mag-form-input .mag-toggle-switch .mag-toggle-input');
var pText = '';
var nextPText = '';
if (switchInput) {
var previousElement = form.querySelector('.mag-toggle-switch').previousElementSibling;
if (previousElement && previousElement.tagName.toLowerCase() === 'p') {
pText = previousElement.textContent.trim();
}
var nextElement = form.querySelector('.mag-toggle-switch').nextElementSibling;
if (nextElement && nextElement.tagName.toLowerCase() === 'p' && switchInput.checked) {
nextPText = nextElement.textContent.trim();
}
var label = switchInput.name || 'SwitchInput';
switchInput.checked ? formData[label] = nextPText : formData[label] = pText;
}
const rating = form.querySelector('.mag-form-element .mag-reviews');
if (rating) {
const parentElement = rating.closest('.mag-form-element');
const labelElement = parentElement.querySelector('.mag-form-label-static').textContent.toLowerCase().replace(/\s+/g, '') || 'ratingstar';
formData[labelElement] = rating.value || null;
}
}
const populateFormFields = (form) => {
form.querySelectorAll('input, textarea, select').forEach(input => {
const savedValue = formData[input.name];
if (savedValue !== undefined) {
if (input.type === 'file') {
} else if (input.type === 'checkbox') {
input.checked = savedValue === 'true';
} else if (input.type === 'radio') {
input.checked = input.value === savedValue;
} else {
input.value = savedValue;
}
}
});
}
const changePage = (curr, newPageIndex) => {
if (curr.querySelector('input[type="hidden"]')) {
updateHiddenInputs(curr);
}
var currentPageIndex = newPageIndex;
const newPageContainer = getElements(currentPageIndex);
const formElement = curr.querySelector('.mag-element-form');
while (formElement.children.length > 1) {
formElement.removeChild(formElement.firstChild);
}
formElement.insertBefore(newPageContainer, formElement.lastChild);
populateFormFields(formElement);
renderPaginationControls(formElement, newPageIndex);
const progressBarSteps = document.querySelectorAll('.mag-FormBuilder-step');
progressBarSteps.forEach((step, index) => {
step.classList.remove('mag-FormBuilder-line-completed', 'mag-FormBuilder-line-last', 'active', 'completed');
if (index < newPageIndex) {
step.classList.add('completed', 'mag-FormBuilder-line-completed');
}
if (index === newPageIndex) {
step.classList.add('active');
}
if (index === newPageIndex + 1) {
step.classList.add('mag-FormBuilder-line-last');
}
});
}
const fetchCustomerData = async () => {
const customer_data = [];
const cid = __st.cid;
if (cid) {
const cdata = new FormData();
cdata.append('customer_id', cid);
cdata.append('shop', Shopify.shop);
await fetch(`${domain}getCustomer`, {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: cdata,
})
.then(res => res.json())
.then(response => {
customer_data.push(response);
});
}
return customer_data;
}
const getMaxFolderSize = (freePlan, planId) => {
if (freePlan !== 0 && !planId) {
return [2000000, 25000000];
} else if (freePlan === 0 && (planId == 1 || planId == 3)) {
return [30000000, 1000000000];
} else if (freePlan === 0 && (planId == 2 || planId == 4)) {
return [100000000, 10000000000];
}
return 0;
};
const validateFileSize = async (input, formToken, url) => {
const response = await fetch(`${domain}getFormData?token=${formToken}&shop=${Shopify.shop}&url=${url}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
});
const data = await response.json();
const freePlan = data[1].free_plan;
const planId = data[1].planId;
const files = Array.from(input.files);
const totalSize = calculateTotalFileSize(files);
var maxFolderSize = 0;
var maxFileSize = 0;
var errorMsg = '';
var size = getMaxFolderSize(freePlan, planId);
maxFileSize = size[0];
if (data[1].folderSize > size[1]) {
maxFolderSize = size[1];
errorMsg += `Maximum allowed folder size of ${(maxFolderSize / 1000000)} MB exceeded.
`;
}
if (totalSize > maxFileSize) {
errorMsg += settings.FileSizeLimitMessage || `Maximum allowed file size of ${(maxFileSize / 1000000)} MB exceeded.
`
}
return errorMsg;
};
const calculateTotalFileSize = (files) => {
let totalSize = 0;
files.forEach(file => {
totalSize += file.size;
});
return totalSize;
};
const getPageElement = (input) => {
const pageIndex = input.getAttribute('data-pageid');
const pageId = pageIndex - 1;
const fieldId = input.getAttribute('data-fieldid');
const page = data.formElements[pageId];
if (page) {
return page.elements.find(element => element.fieldId == fieldId) || null;
}
};
const handleValidationAndDisplayErrors = async () => {
const formData = forms;
let hasErrors = false;
var passwordInput = null;
var confirmPasswordInput = null;
for (const curr of formData) {
const formToken = curr.getAttribute('data-token');
const url = curr.getAttribute('data-url');
const form = document.querySelector('.mag-element-form');
if (form) {
form.querySelectorAll('.error-message').forEach(error => error.remove());
for (const input of form.querySelectorAll('input')) {
const pageElement = getPageElement(input);
if (pageElement) {
const errorMessage = handleValidationMessages(input, pageElement);
if (errorMessage || (input.hasAttribute('required') && input.value.trim() == '')) {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.textContent = errorMessage ? errorMessage : 'This field is required';
input.insertAdjacentElement('afterend', errorMsg);
}
}
if (input.type === 'file' && input.files.length > 0) {
const fileSizeError = await validateFileSize(input, formToken, url);
if (fileSizeError) {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.innerHTML = fileSizeError;
input.insertAdjacentElement('afterend', errorMsg);
}
const acceptTypes = input.getAttribute('accept');
if (acceptTypes) {
const allowedExtensions = acceptTypes.split(',').map(ext => ext.trim().toLowerCase());
for (const file of input.files) {
const fileExtension = `.${file.name.split('.').pop().toLowerCase()}`;
if (!allowedExtensions.includes(fileExtension)) {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.innerHTML = `Invalid file type. Allowed types: ${acceptTypes}`;
input.insertAdjacentElement('afterend', errorMsg);
break;
}
}
}
}
}
for (const textarea of form.querySelectorAll('textarea')) {
const pageElement = getPageElement(textarea);
if (pageElement) {
const errorMessage = handleValidationMessages(textarea, pageElement);
if (errorMessage || (textarea.hasAttribute('required') && textarea.value.trim() === '')) {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.textContent = errorMessage;
textarea.insertAdjacentElement('afterend', errorMsg);
}
}
}
const radioGroups = {};
form.querySelectorAll('input[type="radio"]').forEach((radio) => {
const groupName = radio.getAttribute('name');
if (groupName) {
if (!radioGroups[groupName]) {
radioGroups[groupName] = { radios: [], isRequired: radio.hasAttribute('required') };
}
radioGroups[groupName].radios.push(radio);
}
});
Object.values(radioGroups).forEach(({ radios, isRequired }) => {
if (isRequired) {
const isChecked = radios.some((radio) => radio.checked);
if (!isChecked) {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.textContent = 'Please select an option.';
radios[radios.length - 1].closest('.mag-form-element').insertAdjacentElement('beforeend', errorMsg);
}
}
});
for (const select of form.querySelectorAll('select')) {
if (select.hasAttribute('required')) {
const selectedValue = select.value.trim();
if (!selectedValue || selectedValue == '') {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.textContent = 'Please select a valid option.';
select.insertAdjacentElement('afterend', errorMsg);
}
}
}
for (const multilineGroup of form.querySelectorAll('.mag-form-multiline-element')) {
const pageElement = getPageElement(multilineGroup);
if (pageElement && pageElement.contentValue.required) {
const inputs = multilineGroup.querySelectorAll('.mag-form-multilineele-text');
const hasValue = Array.from(inputs).some(input => input.value.trim() !== '');
if (!hasValue) {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.textContent = 'This field is required.';
multilineGroup.insertAdjacentElement('beforeend', errorMsg);
}
}
}
for (const multiColumnGroup of form.querySelectorAll('.mag-form-multi-column-raw')) {
const pageElement = getPageElement(multiColumnGroup);
if (pageElement && pageElement.contentValue.required) {
const inputs = multiColumnGroup.querySelectorAll('.mag-form-multicolumnele-text');
const hasValue = Array.from(inputs).some(input => input.value.trim() !== '');
if (!hasValue) {
hasErrors = true;
const errorMsg = document.createElement('div');
errorMsg.setAttribute('class', 'error-message');
errorMsg.textContent = 'This field is required.';
multiColumnGroup.insertAdjacentElement('afterend', errorMsg);
}
}
}
for (const addressGroup of form.querySelectorAll(".mag-address-element-wrapper")) {
const pageElement = getPageElement(addressGroup);
if (pageElement && pageElement.contentValue.required) {
addressGroup.querySelectorAll("input, select").forEach((input) => {
if (input.hasAttribute("required") && input.value.trim() === "") {
hasErrors = true;
}
});
if (hasErrors) {
hasErrors = true;
const errorMsg = document.createElement("div");
errorMsg.setAttribute('class', 'error-message');
errorMsg.textContent = "Please fill in all required address fields.";
addressGroup.insertAdjacentElement("afterend", errorMsg);
}
}
}
const quantityInputs = document.querySelectorAll(".mag-quantity-input");
var isValid = false;
quantityInputs.forEach((input) => {
const quantityValue = parseInt(input.value, 10);
let errorMessage = input.closest(".mag-form-element").querySelector(".error-message");
if (isNaN(quantityValue) || quantityValue <= 0) {
isValid = false;
if (!errorMessage) {
errorMessage = document.createElement("div");
errorMessage.classList.add("error-message");
errorMessage.textContent = "Quantity must be at least 1.";
input.closest(".mag-form-element").appendChild(errorMessage);
}
} else {
if (errorMessage) errorMessage.remove();
}
});
if (isValid) {
form.submit(); // Submit only if all inputs are valid
}
document.querySelectorAll(".mag-minus-button, .mag-add-button").forEach((button) => {
button.addEventListener("click", function () {
const input = this.closest(".mag-form-input").querySelector(".mag-quantity-input");
let value = parseInt(input.value, 10) || 0;
if (this.classList.contains("mag-minus-button")) {
value = Math.max(1, value - 1);
} else {
value += 1;
}
input.value = value;
const errorMessage = input.closest(".mag-form-element").querySelector(".error-message");
if (errorMessage && value > 0) {
errorMessage.remove();
}
});
});
}
}
return hasErrors;
};
const handleEmailChange = (event) => {
const email = event.target.value;
const emailDomain = email.split('@').pop();
formData.email = email;
formData.emailDomain = emailDomain;
};
const handleSubmit = async (event, form1) => {
const form = event.target.closest('.mag-form');
if (!form) return;
const submitButton = form.querySelector('button[type="submit"]');
const originalButtonText = submitButton.innerHTML;
if (submitButton) {
submitButton.innerHTML = 'Submitting...';
submitButton.setAttribute('disabled', 'true');
}
const dataToken = form.getAttribute('data-token');
const customerData = await fetchCustomerData();
if (form.querySelectorAll('input[type="hidden"]')) {
updateHiddenInputs(form);
}
formData['hiddenValues'] = hiddenValues;
const restrictedDomains = settings?.RestrictedEmailDomains || [];
const restrictedDomainMessage = settings?.RestrictedDomainMessage || 'Email domain is not allowed';
const email = formData.email || customerData[0]?.email;
const emailDomain = email?.split('@').pop();
let errorMessageContainer = form.querySelector('.error-message');
if (!errorMessageContainer) {
errorMessageContainer = document.createElement('div');
errorMessageContainer.className = 'error-message';
errorMessageContainer.style.color = 'red';
errorMessageContainer.style.display = 'none';
errorMessageContainer.style.padding = '0 8px';
const customizationButtonsDiv = form.querySelector('.mag-appearance-color-customisation-buttons');
customizationButtonsDiv?.insertAdjacentElement('afterend', errorMessageContainer);
}
if (restrictedDomains.includes(emailDomain)) {
errorMessageContainer.textContent = restrictedDomainMessage;
errorMessageContainer.style.display = 'block';
submitButton.innerHTML = originalButtonText || 'Submit';
submitButton.removeAttribute('disabled');
return;
}
errorMessageContainer.style.display = 'none';
const formDatas = new FormData();
if (customerData.length) {
formDatas.append('Customer_first_name', customerData[0].firstName);
formDatas.append('Customer_last_name', customerData[0].lastName);
formDatas.append('Customer_email', customerData[0].email);
}
if (formData.emailArray?.length) {
formDatas.append('emailArray', JSON.stringify(formData.emailArray));
}
formDatas.append('formToken', dataToken);
Object.entries(formData).forEach(([key, value]) => {
if (key !== 'emailArray') formDatas.append(key, value);
});
formDatas.append('submitted_from', window.location.origin + window.location.pathname);
try {
const response = await fetch(`${domain}sendMail?shop=${Shopify.shop}`, {
method: "POST",
headers: { 'Accept': 'application/json' },
body: formDatas
});
const result = await response.json();
if (result.success == 1) {
handleSuccess(form);
} else if (result.success == 0) {
document.querySelector('.mag-toast').classList.add('active');
setTimeout(() => {
document.querySelector('.mag-toast').classList.remove('active');
}, 3000);
}
} catch (error) {
console.error('Form submission error:', error);
} finally {
if (submitButton) {
submitButton.innerHTML = originalButtonText;
submitButton.removeAttribute('disabled');
}
}
};
document.addEventListener('DOMContentLoaded', () => {
const emailInput = document.querySelector('input[type="email"]');
if (emailInput) {
emailInput.addEventListener('input', handleEmailChange);
}
const form = document.querySelector('.mag-form');
if (form) {
form.addEventListener('submit', handleSubmit);
}
});
const handleSuccess = (form) => {
document.querySelector('.modal-dialog.modal-confirm').style.display = 'block';
document.querySelector('.back-shadow').style.display = 'block';
document.body.classList.add('mag-overflow');
const action = afterSubmit.ActionAfterSubmit;
if (action === 'clear_form') {
formData = {};
document.querySelector('.mag-form .mag-form-builder-form>form')?.reset();
} else if (action === 'hide_form') {
document.querySelector('.mag-frame-content').style.display = 'none';
const header = document.querySelector('.mag-form-builder-header');
if (header) {
header.style.display = 'none';
}
const progressBar = document.querySelector('.mag-FormBuilder-process');
if (progressBar) {
progressBar.style.display = 'none';
}
} else if (action === 'redirect_to_page') {
window.location.href = afterSubmit.RedirectLink;
}
currentPageIndex = 0;
changePage(form, currentPageIndex);
};
const updateHiddenInputs = (form) => {
var formElements = data?.formElements;
formElements.forEach((page) => {
page.elements.forEach((element) => {
if (element.elementType === 'HiddenInput' && element.contentValue.dynamicHiddenValue) {
var dynamicHiddenValue = element.contentValue.dynamicHiddenValue;
var { pageId, fieldId, elementType } = dynamicHiddenValue;
var elementLabel = dynamicHiddenValue.contentValue.label;
var matchingPage = formElements.find(p => p.pageid === pageId);
if (matchingPage) {
var matchingElement = matchingPage.elements.find(e =>
e.fieldId === fieldId &&
e.elementType === elementType &&
e.contentValue.label === elementLabel
);
if (matchingElement) {
var inputElement = form.querySelector(`input[type="${jsonToHtml[elementType]}"][data-pageid="${pageId}"][data-fieldid="${fieldId}"]`);
if (inputElement) {
var elementValue = inputElement.value;
var hiddenInput = form.querySelector(`input[type="hidden"][data-pageid="${page.pageid}"][data-fieldid="${element.fieldId}"]`);
if (hiddenInput) {
hiddenInput.value = elementValue;
let hiddenInputs = form.querySelectorAll(`input[type="hidden"][data-pageid="${page.pageid}"][data-fieldid="${element.fieldId}"]`);
hiddenInputs.forEach((hiddenInput) => {
hiddenValues.push(hiddenInput.value);
});
}
}
}
}
}
});
});
};
const getElements = (pageIndex) => {
const page = data.formElements[pageIndex];
const pageContainer = document.createElement('div');
pageContainer.className = 'form-floating';
pageContainer.setAttribute('data-pageid', page.pageid);
page.elements.forEach((pageElement) => {
const wrapper = document.createElement('div');
if (['CheckboxInput', 'AcceptTermsInput', 'RadioInput'].includes(pageElement.elementType)) {
wrapper.setAttribute('class', `mag-form-element ${handleAppearanceStyleClassAppend(1)} ${pageElement.contentValue.customClass}`);
} else if (['RangeBarInput', 'SwitchInput', 'ImageOptionsInput', 'ProductInput', 'ColorSwatchInput'].includes(pageElement.elementType)) {
wrapper.setAttribute('class', `mag-form-element ${pageElement.contentValue.customClass}`);
} else if (pageElement.elementType === 'ButtonInput') {
wrapper.setAttribute('class', `mag-form-element mag-form-button-group ${handleAppearanceStyleClassAppend(2)} ${pageElement.contentValue.customClass}`);
} else if (pageElement.elementType === 'QuantityInput') {
wrapper.setAttribute('class', `mag-form-element mag-quantity-element ${handleAppearanceStyleClassAppend(2)} ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(2) === 'mag-classic-input' || handleAppearanceStyleClassAppend(2) === 'mag-flat-input' || handleAppearanceStyleClassAppend(2) === 'mag-line-input' ? 'mag-defult-element mag-quantity-not-radius' : handleAppearanceStyleClassAppend(1)} ${handleAppearanceStyleClassAppend(2) === 'mag-classic-input-radius' || handleAppearanceStyleClassAppend(2) === 'mag-flat-input-radius' ? 'mag-defult-element mag-classic-quantity-radius' : handleAppearanceStyleClassAppend(1)}`);
} else if (pageElement.elementType === 'HiddenInput') {
wrapper.setAttribute('class', `mag-form-floating mag-form-element mag-hidden-element ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(1)}`);
} else if (pageElement.elementType === 'HTMLInput') {
wrapper.setAttribute('class', `mag-form-floating mag-form-element mag-html-element ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(1)}`);
} else if (pageElement.elementType === 'HeaderInput') {
wrapper.setAttribute('class', `mag-form-element-header-element ${pageElement.contentValue.customClass}`);
} else if (pageElement.elementType === 'ParagraphInput' || pageElement.elementType === 'FeedBackInput' || pageElement.elementType === 'ColorInput' || pageElement.elementType === 'RatingStarInput') {
wrapper.setAttribute('class', `mag-form-floating mag-form-element ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(1)}`);
} else if (pageElement.elementType === 'SelectOptionInput' || pageElement.elementType === 'CountryInput') {
wrapper.setAttribute('class', `mag-form-floating mag-form-element mag-label-shrink ${pageElement.elementType == 'MultiLineInput' ? 'mag-form-multiline-element' : ''} ${pageElement.elementType == 'MultiColumnInput' ? 'mag-form-multicolumn-element' : ''} ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(1)} ${handleAppearanceStyleClassAppend(2)}`);
} else if (pageElement.elementType === 'DatePickerInput' || pageElement.elementType === 'TimePickerInput') {
wrapper.setAttribute('class', `mag-form-floating mag-form-element mag-label-shrink ${pageElement.elementType == 'MultiLineInput' ? 'mag-form-multiline-element' : ''} ${pageElement.elementType == 'MultiColumnInput' ? 'mag-form-multicolumn-element' : ''} ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(1)} ${handleAppearanceStyleClassAppend(2)}`);
} else if (pageElement.elementType === 'Address') {
wrapper.setAttribute('class', `mag-form-floating mag-form-element mag-address-element mag-label-shrink ${pageElement.elementType == 'MultiLineInput' ? 'mag-form-multiline-element' : ''} ${pageElement.elementType == 'MultiColumnInput' ? 'mag-form-multicolumn-element' : ''} ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(1)} ${handleAppearanceStyleClassAppend(2)}`);
} else {
wrapper.setAttribute('class', `mag-form-floating mag-form-element ${pageElement.elementType == 'MultiLineInput' ? 'mag-form-multiline-element' : ''} ${pageElement.elementType == 'MultiColumnInput' ? 'mag-form-multicolumn-element' : ''} ${pageElement.contentValue.customClass} ${handleAppearanceStyleClassAppend(1)} ${handleAppearanceStyleClassAppend(2)}`);
if (pageElement.elementType == 'MultiLineInput') {
wrapper.setAttribute('data-pageid', pageIndex + 1);
wrapper.setAttribute('data-fieldid', pageElement.fieldId);
if (pageElement.contentValue.required) {
wrapper.setAttribute('required', 'true');
}
}
}
settings.CustomHtmlClass ? wrapper.classList.add(`${settings.CustomHtmlClass}`) : '';
let sizeClass = pageElement.contentValue.sizeInPercentage === "100" ? 'mag-layout-col-1' :
pageElement.contentValue.sizeInPercentage === "50" ? 'mag-layout-col-2' :
pageElement.contentValue.sizeInPercentage === "33" ? 'mag-layout-col-3' : null;
if (sizeClass) {
wrapper.classList.add(sizeClass);
}
if (pageElement.elementType !== 'Submit') {
const labelTag = createLabel(pageElement);
var descp = '';
descp = document.createElement('div');
descp.innerHTML = pageElement.contentValue.description ? pageElement.contentValue.description : '';
const name = pageElement.contentValue.label ? pageElement.contentValue.label : '';
switch (pageElement.elementType) {
case 'SelectOptionInput':
case 'CountryInput':
var selectOption = createDropDown(pageElement, name, pageIndex);
labelTag.setAttribute('class', 'mag-form-label');
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(selectOption);
break;
case 'FeedBackInput':
var feedbackInput = renderFeedBackInput(pageElement);
labelTag.setAttribute('class', 'mag-form-label-static-feedback mag-form-label');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(feedbackInput);
break;
case 'TextareaInput':
var textarea = createTextarea(pageElement, pageIndex);
labelTag.setAttribute('class', 'mag-form-label');
if (pageElement.contentValue.hideLabel === false) {
wrapper.appendChild(labelTag);
}
wrapper.appendChild(textarea);
break;
case 'MultiLineInput':
// var multiline = createMultilineInput(pageElement);
labelTag.setAttribute('class', 'mag-form-label');
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
pageElement.contentValue.lines.forEach((line, index) => {
const multilineEle = document.createElement('input');
multilineEle.setAttribute('type', 'text');
multilineEle.setAttribute('class', `mag-form-control mag-form-multilineele-text`);
multilineEle.setAttribute('placeholder', line.placeholder || '');
multilineEle.style.width = pageElement.contentValue.sizeInPercentage ? `${pageElement.contentValue.sizeInPercentage}%` : '100%';
if (line.value) {
multilineEle.value = line.value;
}
wrapper.appendChild(multilineEle);
});
break;
case 'Address':
const addresswrapper = document.createElement('div');
addresswrapper.setAttribute('class', 'mag-address-element-wrapper');
addresswrapper.setAttribute('data-label', pageElement.contentValue.label);
addresswrapper.setAttribute('data-pageid', pageIndex + 1);
addresswrapper.setAttribute('data-fieldid', pageElement.fieldId);
if (pageElement.contentValue.required) {
addresswrapper.setAttribute('required', true);
}
labelTag.setAttribute('class', 'mag-form-label');
pageElement.contentValue.hideLabel === false ? addresswrapper.appendChild(labelTag) : '';
const addressline1 = document.createElement('input');
addressline1.setAttribute('type', 'text');
addressline1.setAttribute('name', 'addressline1');
addressline1.setAttribute('class', `mag-form-control`);
addressline1.setAttribute('placeholder', "Address Line 1");
addressline1.style.width = pageElement.contentValue.sizeInPercentage ? `${pageElement.contentValue.sizeInPercentage}%` : '100%';
addresswrapper.appendChild(addressline1);
const addressline2 = document.createElement('input');
addressline2.setAttribute('type', 'text');
addressline2.setAttribute('name', 'addressline2');
addressline2.setAttribute('class', `mag-form-control`);
addressline2.setAttribute('placeholder', "Address Line 2");
addressline2.style.width = pageElement.contentValue.sizeInPercentage ? `${pageElement.contentValue.sizeInPercentage}%` : '100%';
addresswrapper.appendChild(addressline2);
const city = document.createElement('input');
city.setAttribute('type', 'text');
city.setAttribute('name', 'city');
city.setAttribute('class', `mag-form-control mag-layout-col-3`);
city.setAttribute('placeholder', "City");
city.style.width = pageElement.contentValue.sizeInPercentage ? `${pageElement.contentValue.sizeInPercentage}%` : '100%';
addresswrapper.appendChild(city);
const zipcode = document.createElement('input');
zipcode.setAttribute('type', 'text');
zipcode.setAttribute('name', 'zipcode');
zipcode.setAttribute('class', `mag-form-control mag-layout-col-3`);
zipcode.setAttribute('placeholder', "Zipcode");
zipcode.style.width = pageElement.contentValue.sizeInPercentage ? `${pageElement.contentValue.sizeInPercentage}%` : '100%';
zipcode.addEventListener('input', function (event) {
this.value = this.value.replace(/\D/g, '');
});
zipcode.addEventListener('paste', function (event) {
event.preventDefault();
const pasteData = (event.clipboardData || window.clipboardData).getData('text');
if (!/^\d+$/.test(pasteData)) {
return;
}
this.value = pasteData;
});
addresswrapper.appendChild(zipcode);
const country = document.createElement('select');
country.setAttribute('class', `mag-form-select mag-dropdown`);
country.setAttribute('name', 'country');
checkDependentElement(pageElement, country);
countriesForAdd.forEach((Options, index) => {
const option = document.createElement('option');
option.setAttribute('value', Options.value);
option.setAttribute('key', index);
option.textContent = Options.label;
country.appendChild(option);
});
addresswrapper.appendChild(country);
wrapper.appendChild(addresswrapper);
break;
case 'MultiColumnInput':
var multiline = createMultiColumnInput(pageElement, pageIndex);
labelTag.setAttribute('class', 'mag-form-label');
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(multiline);
break;
case 'ProductInput':
var product = createProducts(pageElement, name);
labelTag.setAttribute('class', 'mag-form-defult');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(product);
break;
case 'HTMLInput':
var htmlContainer = document.createElement('div');
htmlContainer.className = 'html-content-container';
htmlContainer.innerHTML = pageElement.contentValue.htmlContent || '';
if (pageElement.contentValue.htmlContent !== null) {
wrapper.classList.remove('mag-html-element');
wrapper.appendChild(htmlContainer);
}
break;
case 'HeaderInput':
var header = createHeaderInput(pageElement);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(header);
break;
case 'ParagraphInput':
var paragraph = createParagraphInput(pageElement);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(paragraph);
break;
case 'DividerInput':
var divider = document.createElement('hr');
wrapper.className = 'mag-divider ';
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(divider);
break;
case 'ImageOptionsInput':
var image = createImages(pageElement, name);
labelTag.setAttribute('class', 'mag-form-defult mag-form-label');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(image);
break;
case 'RangeBarInput':
var minRange = pageElement.contentValue.minRange !== null ? pageElement.contentValue.minRange : 0;
var maxRange = pageElement.contentValue.maxRange !== null ? pageElement.contentValue.maxRange : 100;
var defaultRange = pageElement.contentValue.defaultRange !== null ? pageElement.contentValue.defaultRange : minRange;
var rangeBar = createRangeBar(pageElement, name, minRange, maxRange, defaultRange);
handleRangeBarEvents(rangeBar);
labelTag.setAttribute('class', 'mag-form-label-static mag-form-label');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
if (!pageElement.contentValue.hideLabel) {
wrapper.appendChild(labelTag);
}
var divWrapper = document.createElement('div');
divWrapper.setAttribute('class', 'mag-form-input-static');
divWrapper.style.position = 'relative';
var minMaxWrapper = document.createElement('div');
minMaxWrapper.style.display = 'flex';
minMaxWrapper.style.justifyContent = 'space-between';
var minLabel = document.createElement('span');
minLabel.setAttribute('class', 'mag-form-label');
minLabel.textContent = minRange.toString();
var maxLabel = document.createElement('span');
maxLabel.setAttribute('class', 'mag-form-label');
maxLabel.textContent = maxRange.toString();
minMaxWrapper.appendChild(minLabel);
minMaxWrapper.appendChild(maxLabel);
divWrapper.appendChild(rangeBar);
divWrapper.appendChild(minMaxWrapper);
wrapper.appendChild(divWrapper);
break;
case 'RatingStarInput':
const divElement = document.createElement('div');
divElement.classList = 'mag-form-rating-star';
wrapper.classList.remove('mag-form-floating');
for (let i = 1; i <= 5; i++) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.setAttribute("width", "18");
svg.setAttribute("height", "18");
svg.setAttribute("fill", `${backgroundColorRgb}`);
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("star-data", i);
svg.setAttribute("class", "bi bi-star-fill mag-reviews");
svg.setAttribute("viewBox", "0 0 16 16");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", "M3.612 15.443c-.386.198-.824-.149-.746-.592l.83-4.73L.173 6.765c-.329-.314-.158-.888.283-.95l4.898-.696L7.538.792c.197-.39.73-.39.927 0l2.184 4.327 4.898.696c.441.062.612.636.282.95l-3.522 3.356.83 4.73c.078.443-.36.79-.746.592L8 13.187l-4.389 2.256z");
svg.appendChild(path);
divElement.appendChild(svg);
}
labelTag.setAttribute('class', 'mag-form-label');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(divElement);
reviewValueChange(divElement);
break;
case 'SwitchInput':
var divWrapper1 = document.createElement('div');
divWrapper1.setAttribute('class', `mag-form-input`);
var divWrapper3 = document.createElement('div');
divWrapper3.setAttribute('class', 'mag-toggle-switch');
if (pageElement.contentValue.firstFieldName) {
var p1 = document.createElement('p');
p1.textContent = pageElement.contentValue.firstFieldName;
divWrapper1.appendChild(p1);
}
var input = document.createElement('input');
input.setAttribute('class', 'mag-toggle-input');
input.setAttribute('name', name);
input.setAttribute('id', `mag-toggle-card${pageElement.fieldId}`);
input.setAttribute('type', 'checkbox');
input.defaultChecked = pageElement.contentValue.defaultToggle || false;
input.required = pageElement.contentValue.required || false;
divWrapper3.appendChild(input);
const toggleLabel = document.createElement('label');
toggleLabel.setAttribute('class', 'mag-toggle-label');
toggleLabel.setAttribute('for', `mag-toggle-card${pageElement.fieldId}`);
divWrapper3.appendChild(toggleLabel);
divWrapper1.appendChild(divWrapper3);
if (pageElement.contentValue.secondFieldName) {
var p2 = document.createElement('p');
p2.textContent = pageElement.contentValue.secondFieldName;
divWrapper1.appendChild(p2);
}
labelTag.setAttribute('class', 'mag-label-default-switch-style mag-form-label');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(divWrapper1);
break;
case 'QuantityInput':
var quantityInput = createQuantityInputElement(pageElement, name, pageIndex);
labelTag.setAttribute('class', 'mag-form-label mag-label-default');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(quantityInput);
break;
case 'ColorSwatchInput':
const swatchWrapper = document.createElement('div');
swatchWrapper.classList.add('mag-form-color-swatch-container');
let previouslySelectedLabel = null;
pageElement.contentValue.colorPairs.forEach((colorPair, index) => {
const colorSwatch = document.createElement('div');
colorSwatch.classList.add('color-swatch');
colorSwatch.setAttribute('title', colorPair.label || `Color ${index + 1}`);
const input = document.createElement('input');
input.setAttribute('type', 'radio');
input.setAttribute('name', name);
input.setAttribute('class', 'mag-color-swatch-input');
input.setAttribute('value', colorPair.value);
const label = document.createElement('label');
label.setAttribute('class', 'mag-color-swatch-label mag-form-label');
label.style.backgroundColor = colorPair.value;
if (colorPair.defaultSelected) {
label.classList.add('selected');
input.checked = true;
previouslySelectedLabel = label;
}
input.addEventListener('change', function () {
if (previouslySelectedLabel) {
previouslySelectedLabel.classList.remove('selected');
}
label.classList.add('selected');
previouslySelectedLabel = label;
});
colorSwatch.appendChild(input);
colorSwatch.appendChild(label);
swatchWrapper.appendChild(colorSwatch);
});
const hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', pageElement.fieldId);
hiddenInput.setAttribute('readonly', '');
hiddenInput.setAttribute('value', pageElement.contentValue.colorPairs.find(cp => cp.defaultSelected)?.value || '');
labelTag.classList.add('mag-form-label-static');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
checkDependentElement(pageElement, labelTag);
wrapper.classList.remove('mag-form-floating');
if (!pageElement.contentValue.hideLabel) {
wrapper.appendChild(labelTag);
}
wrapper.appendChild(swatchWrapper);
wrapper.appendChild(hiddenInput);
break;
default:
var inputElement = createInputElement(pageElement, name, pageIndex);
if (pageElement.elementType === 'AcceptTermsInput') {
var divWrapper = document.createElement('div');
divWrapper.setAttribute('class', `mag-form-terms-label ${handleAppearanceStyleClassAppend(3)}`);
divWrapper.appendChild(inputElement);
labelTag.setAttribute('class', 'mag-form-label-static');
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(divWrapper);
}
else if (pageElement.elementType === 'CheckboxInput') {
labelTag.setAttribute('class', 'mag-form-label-static mag-form-label');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
childernArray = Array.from(inputElement.children);
childernArray.forEach(child => {
if (child.nodeType === Node.ELEMENT_NODE) {
const divWrapper = document.createElement('div');
divWrapper.appendChild(child);
wrapper.appendChild(divWrapper);
}
})
checkDependentElement(pageElement, labelTag);
}
else if (pageElement.elementType === 'RadioInput') {
labelTag.setAttribute('class', 'mag-label-radio-default mag-form-label');
labelTag.setAttribute('data-label', pageElement.contentValue.label);
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(inputElement);
checkDependentElement(pageElement, labelTag);
}
else if (pageElement.elementType === 'ButtonInput') {
var divWrapper = document.createElement('div');
divWrapper.setAttribute('class', 'mag-form-defalt');
divWrapper.appendChild(inputElement);
labelTag.setAttribute('data-label', pageElement.contentValue.label);
labelTag.setAttribute('class', 'mag-form-label mag-form-defalt');
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(divWrapper);
checkDependentElement(pageElement, labelTag);
}
else {
labelTag.setAttribute('class', 'mag-form-label');
pageElement.contentValue.hideLabel === false ? wrapper.appendChild(labelTag) : '';
wrapper.appendChild(inputElement);
}
break;
}
wrapper.appendChild(descp);
if (pageElement.elementType === 'FileInput' || pageElement.elementType === 'SignatureInput') {
labelTag.classList.add('mag-form-label-style', 'mag-form-label');
if (pageElement.contentValue.hint) {
const hint = document.createElement('small');
hint.textContent = pageElement.contentValue.hint
wrapper.appendChild(hint);
}
}
}
pageContainer.appendChild(wrapper);
});
if (reCaptcha?.recaptcha_status == '1' && myappgurussettings?.recaptcha_type == 'v2') {
const recaptchaContainer = document.createElement('div');
recaptchaContainer.id = 'html_element';
pageContainer.appendChild(recaptchaContainer);
}
return pageContainer;
}
const handleInputFocusBlur = () => {
const inputFields = document.querySelectorAll(".mag-form-control"),
dropdownfields = document.querySelectorAll(".mag-dropdown"),
quantity = document.querySelectorAll(".mag-quantity-input");
inputFields.forEach((inputField) => {
if (inputField?.value?.trim() !== "") {
inputField.closest(".mag-form-floating")?.classList.add("mag-label-shrink");
}
inputField.addEventListener("focus", () => {
inputField.closest(".mag-form-floating")?.classList.add("mag-label-shrink");
});
inputField.addEventListener("blur", () => {
if (inputField?.value?.trim() === "") {
inputField.closest(".mag-form-floating")?.classList.remove("mag-label-shrink");
}
});
inputField.addEventListener("input", () => {
if (inputField?.value?.trim() !== "") {
inputField.closest(".mag-form-floating")?.classList.add("mag-label-shrink");
}
});
});
quantity.forEach((qty) => {
qty.addEventListener("focus", () => {
qty.closest(".mag-form-element")?.classList.add("mag-label-shrink");
});
qty.addEventListener("blur", () => {
if (qty.value.trim() === "") {
qty.closest(".mag-form-element")?.classList.remove("mag-label-shrink");
}
});
qty.addEventListener("input", () => {
if (qty.value.trim() !== "") {
qty.closest(".mag-form-element")?.classList.add("mag-label-shrink");
}
});
});
}
const renderFeedBackInput = (pageElement) => {
const mainDiv = document.createElement('div');
const feedbackContainer = document.createElement('div');
feedbackContainer.classList.add('mag-form-feedback-preview');
let selectedValue = null;
pageElement.contentValue.options.forEach(option => {
const emoji = document.createElement('div');
emoji.classList.add('mag-form-feedback-preview-inner');
emoji.setAttribute('title', option.value)
const emojiSvg = document.createElement('div');
emojiSvg.setAttribute('class', 'mag-form-feedback-preview-svg');
emojiSvg.innerHTML = option.emoji;
emoji.appendChild(emojiSvg);
emoji.addEventListener('click', () => {
if (selectedValue) {
selectedValue.classList.remove('selected');
}
selectedValue = emoji;
selectedValue.classList.add('selected');
selectedValue.dataset.value = option.value;
});
feedbackContainer.appendChild(emoji);
mainDiv.appendChild(feedbackContainer);
});
return mainDiv;
};
const handleRangeBarEvents = (rangeBar) => {
let tooltip = createTooltip(`${rangeBar.value}`);
rangeBar.addEventListener('mouseenter', (e) => {
tooltip.classList.add('tooltip-active');
tooltip.style.display = 'block';
tooltip.style.position = 'absolute';
tooltip.style.left = `${e.pageX + 10}px`;
tooltip.style.top = `${e.pageY - 30}px`;
tooltip.textContent = `${rangeBar.value}`;
});
rangeBar.addEventListener('mousemove', (e) => {
tooltip.style.left = `${e.pageX + 10}px`;
tooltip.style.top = `${e.pageY - 30}px`;
tooltip.textContent = `${rangeBar.value}`;
});
rangeBar.addEventListener('mouseleave', () => {
tooltip.classList.remove('tooltip-active');
tooltip.style.display = 'none';
});
rangeBar.addEventListener('input', (e) => {
tooltip.textContent = `${e.target.value}`;
});
};
const createTooltip = (text) => {
const tooltip = document.createElement('div');
tooltip.className = 'tooltip';
tooltip.textContent = text;
document.body.appendChild(tooltip);
return tooltip;
}
const form = document.querySelector('.mag-element-form');
if (form) {
form.querySelectorAll('input').forEach(input => {
input.addEventListener('blur', () => handleValidationAndDisplayErrors());
});
}
authenticate(Shopify.shop);