tbxforms
Version:
A Torchbox-flavoured template pack for django-crispy-forms, adapted from crispy-forms-gds
116 lines (115 loc) • 3.41 kB
JavaScript
var tbxforms = "";
function updateVisibility(container, drivingFieldNodeList, conditionalValuesForElement) {
let shouldShow = false;
if (drivingFieldNodeList.length > 1) {
drivingFieldNodeList.forEach(function(field) {
if (field.checked && conditionalValuesForElement.includes(field.value)) {
shouldShow = true;
}
});
} else {
const field = drivingFieldNodeList.item(0);
shouldShow = conditionalValuesForElement.includes(field.value) || conditionalValuesForElement.includes(Number(field.value));
}
container.hidden = !shouldShow;
drivingFieldNodeList.forEach(
(field) => field.setAttribute("aria-expanded", shouldShow.toString())
);
}
function TbxForms(form) {
this.form = form;
const self = this;
form.querySelectorAll("*").forEach(function(formElement) {
if (formElement.dataset.conditionalFieldName && formElement.dataset.conditionalFieldValues) {
const container = formElement.closest(".tbxforms-form-group") ? formElement.closest(".tbxforms-form-group") : formElement;
const drivingFieldNodeList = form.querySelectorAll(
'[name="' + formElement.dataset.conditionalFieldName + '"]'
);
let conditionalValuesForElement;
try {
conditionalValuesForElement = JSON.parse(
formElement.dataset.conditionalFieldValues
);
} catch (e) {
throw "Invalid JSON: " + e;
}
container.classList.add("tbxforms-conditional");
drivingFieldNodeList.forEach(function(field) {
field.addEventListener("change", function() {
updateVisibility(
container,
drivingFieldNodeList,
conditionalValuesForElement
);
});
});
updateVisibility(
container,
drivingFieldNodeList,
conditionalValuesForElement
);
}
});
form.addEventListener("submit", function() {
form.querySelectorAll("[hidden]").forEach(function(hiddenFormElement) {
self.clearInput(hiddenFormElement);
});
});
}
TbxForms.prototype.clearInput = function(node) {
const self = this;
switch (node.tagName) {
case "INPUT":
switch (node.type) {
case "color":
case "date":
case "datetime-local":
case "email":
case "file":
case "hidden":
case "image":
case "month":
case "number":
case "password":
case "range":
case "reset":
case "search":
case "tel":
case "text":
case "time":
case "url":
case "week":
node.value = "";
break;
case "radio":
case "checkbox":
node.checked = false;
break;
default:
console.debug(
`Skipping unsupported node.type '${node.type}' while trying to clearInput().`
);
}
break;
case "TEXTAREA":
node.value = "";
break;
case "SELECT":
node.selectedIndex = -1;
break;
case "DIV":
case "FIELDSET":
node.querySelectorAll("*").forEach(function(formElement) {
self.clearInput(formElement);
});
break;
default:
console.debug(
`Skipping unsupported node.tagName '${node.tagName}' while trying to clearInput().`
);
}
};
TbxForms.selector = function() {
return "form.tbxforms";
};
export { TbxForms as default };