I have JavaScript code, in which I change the input field css class on invalid
event to add an error
class to a parent div
having the class form-row
.
I furthermore attach then an event listener on the form fields fields on input and click to remove the error class once the user interacts with the form fields (text, textarea, dropdown select boxes, …)
Now, those form fields already have event handlers attached, and some stop event propagation.
Certain elements won’t call formElementRow.classList.remove('error');
as some other event handler acts first.
Is there a quick way to force my event handler that I define here to take precdence while still allowing the other event handlers to act on the page?
I control the html of the form, I do not want to change anything with the code that registers the other event handlers.
This is my code that works for all my form elements except those who stop the event propagation:
const formErrorStatesOnBrowserSideValidation = () => {
const targetClass = '.form-row';
document.addEventListener('invalid', (invalidEvent) => {
const {target} = invalidEvent;
const formElementRow = target.closest(targetClass);
if (formElementRow) {
formElementRow.classList.add('error');
}
['input', 'click'].forEach(event => {
// some elements have other js / jQuery applied to them that stops event propagation hence the class removal is never called to those
target.addEventListener(event, () => {
formElementRow.classList.remove('error');
});
});
}, true);
};
formErrorStatesOnBrowserSideValidation();
This is a follow-up question from: What event to listen for when a user clicks submit button in html5 invalid form?