rikschennink/short-and-sweet

The counter does not updates when triggering an "input" event

C-Duv opened this issue · 2 comments

C-Duv commented

TL;DR; How to force an update/refresh of the counter from a script?

I have an input where I added the shortAndSweet counter. It works fine except when I change the input's content/text via JavaScript: the counter does not updates. I have to manually enter a character for it to reflect the actual count.

By looking at short-and-sweet.js I can it listens to 'input' JavaScript event so I should be able to force an update using jQuery.trigger('input').

It does not work: the input's content changes but the counter stays at the same value.

Here is an example
https://jsfiddle.net/ecudkh5j/

Is there a way to achieve this?

Does work when using a normal JavaScript event. https://jsfiddle.net/oz6fd8L4/1/

C-Duv commented

Yes, you are right.
I dont understand why I typed the following answer last week and did not posted it…
Posting it nevertheless for future reference.


It looks like using Vanilla "input" event it works just fine:

shortAndSweet('textarea, input');

setTimeout(
	function() {
		// Change input content
		$('textarea').val('foo');
		// Tell shortAndSweet about it
		$('textarea').get(0).dispatchEvent(new Event('input'))
	},
	1000,
);

My issue must be jQuery-related, sorry for the trouble.

Let's hope it will help others ;)