Handle required attribute on input for PaymentMethod controller

This is done for one reason : do not submit form with required attribute on input that are actually hidden ; this is not handle correctly by browsers.

This idea here is to add/remove the required attribute on each input if the form is visible or not.
This commit is contained in:
Jean-Baptiste Bellet
2021-11-17 11:46:59 +01:00
committed by Matt-Yorkley
parent 3063b041d1
commit 7159cc3ff1
2 changed files with 66 additions and 16 deletions

View File

@@ -3,23 +3,40 @@ export default class extends Controller {
static targets = ["paymentMethod"];
connect() {
this.hideAll();
this.selectPaymentMethod();
}
selectPaymentMethod(event) {
this.hideAll();
const paymentMethodContainerId = event.target.dataset.paymentmethodId;
const paymentMethodContainer = document.getElementById(
paymentMethodContainerId
);
paymentMethodContainer.style.display = "block";
}
hideAll() {
selectPaymentMethod(event = null) {
const paymentMethodContainerId = event
? event.target.dataset.paymentmethodId
: null;
Array.from(
document.getElementsByClassName("paymentmethod-container")
).forEach((e) => {
e.style.display = "none";
if (e.id === paymentMethodContainerId) {
e.style.display = "block";
this.addRequiredAttributeOnInputIfNeeded(e);
} else {
e.style.display = "none";
this.removeRequiredAttributeOnInput(e);
}
});
}
removeRequiredAttributeOnInput(container) {
Array.from(container.getElementsByTagName("input")).forEach((i) => {
if (i.required) {
i.dataset.required = i.required;
i.required = false;
}
});
}
addRequiredAttributeOnInputIfNeeded(container) {
Array.from(container.getElementsByTagName("input")).forEach((i) => {
if (i.dataset.required === "true") {
i.required = true;
}
});
}
}