We have pages that contain 1-3 forms. Each form does have a submit button which is styled as inactive* as long as the user didn't change the form.
Now I need to:
- remove the class from the button as soon as the form changes
- remove the event listener from the form
I came up with this:
for (const form of Array.from(document.getElementsByClassName('form'))) {
const formHandlerChange = event => {
const submit = form.getElementsByClassName('disabled')[0];
submit.classList.remove('disabled');
form.removeEventListener('change', formHandlerChange);
};
form.addEventListener('change', formHandlerChange);
}
Is this a good solution? Is it a bad thing to create formHandlerChange
for each form? Would it be better to get the form each time formHandlerChange
is entered manually and have this function defined only once outside the loop?
* It's also disabled
but I removed it for simplicity of this review.
disabled
class more than once. What I prefer to do, instead of removing the event, is to check some condition. For example:if (submit.classlist.contains('disabled') { ...
\$\endgroup\$enabled
and test this forevent.target
, but this only makes the code more complex than needed, right? What do you think? @MarcRohloff \$\endgroup\$currentTarget
to avoid the lookup. I really don't think either direction would be wrong and you should do what you think is best. My rule of thumb is mostly just to be consistent across your code-base. \$\endgroup\$:disabled
and:enabled
pseudo-classes. developer.mozilla.org/en-US/docs/Web/CSS/:disabled \$\endgroup\$