<div class="form ">
<form id="basic-form" name="basic-form" action="http://localhost:5000/components/preview/raffle-success" method="GET" enctype="application/x-www-form-urlencoded" autocomplete="off" role="presentation" data-custom-validate='{ "toggleSubmit": false }'>
Form content
</form>
</div>
<div class="form {{ className }}">
<form
{{#if id }} id="{{ id }}"{{/if}}
{{#if name }} name="{{ name }}"{{/if}}
{{#if action }} action="{{ action }}"{{/if}}
{{#if method }} method="{{ method }}"{{/if}}
{{#if contentType }} enctype="{{ contentType }}"{{/if}}
{{#unless autocomplete}} autocomplete="off" role="presentation"{{/unless }}
{{#if novalidate }} novalidate{{/if}}
{{#if customValidate }} data-custom-validate='{ "toggleSubmit": {{ toggleSubmit }} }'{{/if}}
{{#if fetchSubmit }} data-fetch-submit='{ "action": "{{ action }}", "method": "{{ method }}", "enctype": "{{ contentType }}" }'{{/if}}
{{#if mountpoint }} data-fetch-mountpoint="{{ mountpoint }}"{{/if}}
>
{{#>@partial-block}}
Form content
{{/@partial-block}}
</form>
</div>
{
"id": "basic-form",
"name": "basic-form",
"action": "http://localhost:5000/components/preview/raffle-success",
"method": "GET",
"contentType": "application/x-www-form-urlencoded",
"autocomplete": false,
"novalidate": false,
"customValidate": true,
"toggleSubmit": false
}
export function serialize(form) {
if (!form || form.nodeName !== "FORM") {
return;
}
var i, j, q = [];
for (i = form.elements.length - 1; i >= 0; i = i - 1) {
if (form.elements[i].name === "") {
continue;
}
switch (form.elements[i].nodeName) {
case 'INPUT':
switch (form.elements[i].type) {
case 'text':
case 'number':
case 'range':
case 'date':
case 'email':
case 'hidden':
case 'password':
case 'button':
case 'reset':
case 'submit':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'checkbox':
case 'radio':
if (form.elements[i].checked) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
}
break;
case 'file':
break;
}
break;
case 'TEXTAREA':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'SELECT':
switch (form.elements[i].type) {
case 'select-one':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
case 'select-multiple':
for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
if (form.elements[i].options[j].selected) {
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
}
}
break;
}
break;
case 'BUTTON':
switch (form.elements[i].type) {
case 'reset':
case 'submit':
case 'button':
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
break;
}
break;
}
}
return q.join("&");
}
import hostnamesConfig from "./hostnames.config";
export const FormAction = (() => {
function setAction() {
const $form = document.querySelector('form');
const hostname = location.hostname;
let destination = 'volvo-leads-api.ddev.site';
let fetchSubmit = $form.getAttribute('data-fetch-submit');
if (hostnamesConfig.isStage()) {
destination = 'leads-api-stage.promotions-volvocars.ch';
} else if (hostnamesConfig.isProduction()) {
destination = 'leads-api.promotions-volvocars.ch';
}
const url = 'https://' + destination + '/v1.0/lead/create';
$form.setAttribute('action', url);
if (fetchSubmit) {
fetchSubmit = JSON.parse(fetchSubmit);
fetchSubmit.action = url;
$form.setAttribute('data-fetch-submit', JSON.stringify(fetchSubmit));
}
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', () => {
setAction();
});
})()
}
})();
export default FormAction;
import { serialize } from './_form-serialize.js';
export { serialize } from './_form-serialize.js';
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
export const FormFetch = (() => {
let form,
language,
request,
responseError,
responseNotice,
mountpoint;
async function submit(event) {
const form = event.target.closest('form');
const submitButton = form.querySelector('button[type="submit"]');
const mode = form.querySelector('input[name="mode"]').value;
const dataset = {
mountpoint: form.dataset.fetchMountpoint
};
const { enctype } = JSON.parse(form.dataset.fetchSubmit);
const disabledFormElements = form.querySelectorAll('[disabled="disabled"]');
disabledFormElements.forEach((el) => {
el.removeAttribute('disabled');
});
const formdata = {
method: form.method,
credentials: 'same-origin',
headers: {
'Authorization': `Token ` + (mode === 'prod' ? '6789012345' : '1234567890'),
'Content-Type': `${enctype || 'application/x-www-form-urlencoded'}; charset=utf-8`
}
};
if (form.method === 'post') {
formdata.body = enctype === 'application/json'
? JSON.stringify(Object.fromEntries(new FormData(form)))
: serialize(form);
}
disabledFormElements.forEach((el) => {
el.setAttribute('disabled', 'disabled');
});
submitButton.disabled = true;
const fetched = await fetch(form.action, formdata)
.then((response) => {
if (response.ok) {
submitButton.disabled = false;
return response.json();
}
})
.catch(function (error) {
submitButton.disabled = false;
return {
success: false
}
});
// trigger doc ready events
window.dispatchEvent(new Event('DOMContentLoaded', {
bubbles: true,
cancelable: true
}));
window.dispatchEvent(new Event('load', {
bubbles: true,
cancelable: true
}));
return fetched;
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', function () {
// refactor this
if (document.documentElement.classList.contains('submitter')) {
return;
}
document.documentElement.classList.add('submitter');
document.body.addEventListener('submit', function (event) {
form = event.target.closest('[data-fetch-submit]');
language = document.querySelector('#language').value;
responseError = document.querySelector('#response_error');
responseNotice = document.querySelector('#response_notice');
if (form) {
event.preventDefault();
if (form.checkValidity()) {
responseError.innerHTML = '';
responseNotice.innerHTML = '';
request = submit(event).then((response) => {
if (response.success) {
// responseNotice.innerHTML = document.querySelector(`[data-notice][data-language="${language}"][data-key="success"]`).innerHTML;
// form.querySelector('button[type="submit"]').remove();
const $thankYou = document.querySelector('.thank-you');
const $formContainer = document.querySelector('.form-container');
if ($thankYou) {
$thankYou.classList.remove('d-none');
}
if ($formContainer) {
$formContainer.classList.add('d-none');
}
} else {
const errorKey = response.error ? response.error : 'default';
responseError.innerHTML = document.querySelector(`[data-error][data-language="${language}"][data-key="${errorKey}"]`).innerHTML;
}
});
}
}
});
});
})()
};
})();
export default FormFetch;
export const FormGetvars = (() => {
function setGetVars() {
const $form = document.querySelector('form');
const vars = _getVariables();
for (let key in vars) {
if (vars.hasOwnProperty(key)) {
let $input = $form.querySelector('input[name="' + key + '"]');
if ($input === null) {
$input = $form.querySelector('textarea[name="' + key + '"]');
}
if ($input !== null) {
$input.value = decodeURI(vars[key]);
if ($input.tagName.toLowerCase() === 'textarea') {
$input.setAttribute('disabled', 'disabled');
}
}
}
}
}
function _getVariables() {
const variables = [];
if (document.location.search) {
let search = document.location.search.substring(1);
search.split('&').forEach((splitValue) => {
let keyValue = splitValue.split('=');
variables[keyValue[0]] = keyValue[1];
});
}
return variables;
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', () => {
setGetVars();
});
})()
}
})();
export default FormGetvars;
import hostnamesConfig from "./hostnames.config";
export const FormHeader = (() => {
function initHeader() {
if (!hostnamesConfig.isFormDomain()) {
document.querySelector('header')?.remove();
}
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', () => {
initHeader();
})
})()
}
})();
export default FormHeader;
import hostnamesConfig from "./hostnames.config";
export const FormMode = (() => {
function setMode() {
const $mode = document.querySelector('input[name="mode"]');
let mode = 'qa';
if (hostnamesConfig.isProduction()) {
mode = 'prod';
}
$mode.value = mode;
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', () => {
setMode();
});
})()
}
})();
export default FormMode;
import hostnamesConfig from "./hostnames.config";
export const FormThankYou = (() => {
function initThankYou() {
const $thankYou = document.querySelector('.thank-you p:first-child');
if (!hostnamesConfig.isFormDomain()) {
$thankYou.style.color = 'inherit';
$thankYou.style.backgroundColor = 'unset';
$thankYou.style.backgroundImage = 'none';
}
}
function updateThankYouModel() {
const $select = document.querySelector('select[id="model"]');
const $thankYouModel = document.querySelector('#thankYouModel');
if ($select && $thankYouModel) {
$select.addEventListener('change', (event) => {
$thankYouModel.innerHTML = event.target.value;
});
$thankYouModel.innerHTML = $select.value;
}
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', () => {
initThankYou();
updateThankYouModel();
})
})()
}
})();
export default FormThankYou;
export const FormUpdateHeight = (() => {
let $body;
const callback = (mutationList, observer) => {
const height = $body.scrollHeight;
top.postMessage(JSON.stringify({
type: 'vppForms',
height: height,
}));
};
function initFormUpdateHeight() {
$body = document.querySelector('body');
const config = {
attributes: true,
childList: true,
subtree: true,
};
const observer = new MutationObserver(callback);
observer.observe($body, config);
window.addEventListener('resize', callback);
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', () => {
initFormUpdateHeight();
});
window.addEventListener('load', callback);
})()
};
})();
export default FormUpdateHeight;
export const FormValidation = (() => {
const errorTypeMap = {
valueMissing: 'required',
patternMismatch: 'pattern',
};
let invalidHandler = {};
function validate(event) {
const form = event.target.closest('form[data-custom-validate]');
const config = form && form.dataset.customValidate && JSON.parse(form.dataset.customValidate);
const buttons = form && form.querySelectorAll('button[type=submit]');
if (!buttons) {
return false;
}
if (form.checkValidity()) {
Array.from(buttons).forEach((button) => {
if (config.toggleSubmit) {
button.disabled = false;
}
});
}
else {
Array.from(buttons).forEach((button) => {
if (config.toggleSubmit) {
button.disabled = true;
}
});
}
}
function submit(event) {
const form = event.target.closest('form');
form.dataset.validate = true;
if (form.checkValidity && !invalidHandler[form.id]) {
invalidHandler[form.id] = true;
form.querySelectorAll('input').forEach((input) => {
input.addEventListener('invalid', isValidField);
input.addEventListener('keyup', isValidField);
input.addEventListener('blur', isValidField);
});
}
if (form.checkValidity && !form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
const invalid = form.querySelector(':invalid');
// console.log('invalid', invalid);
invalid.parentElement.scrollIntoView(false);
}
}
function isValidField(e) {
const errorFields = e.target.parentElement.querySelectorAll('.input__error span');
if (errorFields && errorFields.length > 0) {
errorFields.forEach((errorField) => { errorField.classList.add('d-none') })
Object.keys(errorTypeMap).forEach((errorType) => {
if (!e.target.validity.valid && e.target.validity[errorType]) {
e.target.parentElement.querySelector('[data-error-type="' + errorTypeMap[errorType] + '"]').classList.remove('d-none');
}
});
}
}
return {
init: (() => {
window.addEventListener('DOMContentLoaded', () => {
document.addEventListener('input', validate);
document.addEventListener('change', validate);
document.addEventListener('submit', submit);
const forms = document.querySelectorAll('form');
// suppress html5 error notifications and set unique id
Array.from(forms).forEach(function (form) {
form.id = Math.random().toString(32).substring(2);
form.noValidate = true;
});
});
})()
};
})();
export default FormValidation;
No notes defined.