Fellow JS devs, I have come across a fairly simple question which has puzzled me. When the user submits a form I disable all inputs and submit button changes to a loading animation (fa-spinner
from fontawesome). Once the form submit is complete then I restore the previous state, and enable everything back.
My question comes to making this code more concise and deliberate in a simple toggle function:
function toggleFormElements(toggle, elArr) {
if (toggle == 'disable') {
elArr.btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
elArr.btn.setAttribute('disabled', 'disabled');
// inputs
elArr.fields.forEach((field, i) => {
field.setAttribute('disabled', 'disabled');
});
} else if (toggle == 'enable') {
elArr.btn.innerHTML = 'Submit';
elArr.btn.removeAttribute('disabled');
// inputs
elArr.fields.forEach((field, i) => {
field.removeAttribute('disabled');
});
}
}
Would it be possible to make this code more readable or simply shorter?