This repository has been archived on 2024-10-24. You can view files and clone it, but cannot push or open issues or pull requests.
fradrive-old/frontend/src/utils/form/reactive-submit-button.js
2020-05-12 20:40:46 +02:00

86 lines
2.3 KiB
JavaScript

import { Utility } from '../../core/utility';
const REACTIVE_SUBMIT_BUTTON_INITIALIZED_CLASS = 'reactive-submit-button--initialized';
@Utility({
selector: 'form',
})
export class ReactiveSubmitButton {
_element;
_requiredInputs;
_submitButton;
constructor(element) {
if (!element) {
throw new Error('Reactive Submit Button utility cannot be setup without an element!');
}
this._element = element;
if (this._element.classList.contains(REACTIVE_SUBMIT_BUTTON_INITIALIZED_CLASS)) {
return false;
}
// abort if form has param data-formnorequired
if (this._element.dataset.formnorequired !== undefined) {
throw new Error('Form has formnorequired data attribute. Will skip setup of reactive submit button.');
}
this._requiredInputs = Array.from(this._element.querySelectorAll('[required]'));
if (!this._requiredInputs) {
// abort if form has no required inputs
throw new Error('Submit button has formnorequired data attribute. Will skip setup of reactive submit button.');
}
const submitButtons = Array.from(this._element.querySelectorAll('[type="submit"]'));
if (!submitButtons || !submitButtons.length) {
throw new Error('Reactive Submit Button utility couldn\'t find any submit buttons!');
}
this._submitButton = submitButtons.reverse()[0];
// abort if form has param data-formnorequired
if (this._submitButton.dataset.formnorequired !== undefined) {
return false;
}
this.setupInputs();
this.updateButtonState();
this._element.classList.add(REACTIVE_SUBMIT_BUTTON_INITIALIZED_CLASS);
}
destroy() {
// TODO
}
setupInputs() {
this._requiredInputs.forEach((el) => {
const checkbox = el.getAttribute('type') === 'checkbox';
const eventType = checkbox ? 'change' : 'input';
el.addEventListener(eventType, () => {
this.updateButtonState();
});
});
}
updateButtonState() {
if (this.inputsValid()) {
this._submitButton.removeAttribute('disabled');
} else {
this._submitButton.setAttribute('disabled', 'true');
}
}
inputsValid() {
let done = true;
this._requiredInputs.forEach((inp) => {
const len = inp.value.trim().length;
if (done && len === 0) {
done = false;
}
});
return done;
}
}