Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Input change event not triggered when value is cleared by the user #105

Open
coemans opened this issue Dec 5, 2019 · 1 comment
Open

Comments

@coemans
Copy link

coemans commented Dec 5, 2019

When is the change event triggered? As described in the documentation: change event is fired for <input>, <select>, and <textarea> elements when an alteration to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element's value.

When I've an input element:

<input id="test" type="text"/>

And have the following code:

const input = document.querySelector('#test');
input.value = 'Programmatically set value';
input.addEventListener('change', () => { console.info('the change event was triggered!'); });

The change event will be triggered when the user manually clears the input field. Happy days! But when we set the value using the setAttribute function, no change event will be triggered when the user clears the input element.

const input = document.querySelector('#test');
input.setAttribute('value', 'Programmatically set value');
input.addEventListener('change', () => { console.log('the change event was never triggered!'); });

With both implementations, it is the user who clears the input element. I would expect an event in both cases. It looks like a bug?

@kungfooman
Copy link

kungfooman commented Jan 28, 2023

Any resolution on this?

Manually changing input.value doesn't trigger input event either:

input = document.createElement("input");
document.body.prepend(input);
input.addEventListener("input", console.log);

First use your keyboard to change the value (you should see console log messages). Then use this code:

input.value += "asd"

(I don't see anything in console)

So I assume the only correct way so far is:

function inputSetValue(element, value) {
  element.value = value;
  element.dispatchEvent(new InputEvent("input"));
}
inputSetValue(input, input.value + "asd");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants