Stwosch
Stwosch

Reputation: 642

Why changing input value manually can't emit input event?

Code is defined in attachment

I have a situation, where I have an input field and input event attached to the field.

When I'm writing, removing etc. from this field, the event is emitted properly and I can react to this event.

input.addEventListener('input', () => {
    changeCounterValue(charsCounter, input);
});

But when I submit a form with the input, I reset the value of the input, but it actually doesn't trigger my input event.

document.querySelector('form').addEventListener('submit', (e) => {
    e.preventDefault();
    input.value = "";
  // I don't want to integrate here with charsCounter module, to reset his value to 0
});

My goal is to reset the value charsCounter without integreating in charsCounter module, because in this moment when I submit the form, charsCounter doesn't reset to 0.

Upvotes: 1

Views: 345

Answers (1)

Tom M
Tom M

Reputation: 2904

Natively, as @Temani Afif stated in the comments, the input event will not be triggered by changes from Javascript. Instead, you have to dispatch it yourself after resetting your value. Create the Element like this:

 var inputEvent = new Event('input', {
    view: window,
    bubbles: true,
    cancelable: true
});

And trigger it in your submit EventListener like this:

document.querySelector('form').addEventListener('submit', (e) => {
    e.preventDefault();
    input.value = "";
    // I don't want to integrate here with charsCounter module, to reset his value to 0
    input.dispatchEvent(inputEvent);
});

JSFiddle

For further information, visit MDN - Creating and triggering Events

Upvotes: 1

Related Questions