0

I have a code which needs to trigger the input event manually on an input with a datepicker.

The code looks like:

input.on('apply.daterangepicker', function(e) {
    input.trigger('input');
});

input.on('input', function(e) {
    console.log('11111111111111111111');
});

document.getElementById('filter-created-at').addEventListener('input', function(e) {
    console.log('22222222222222222222');
});

The first jQuery event listener works fine. But the second pure JavaScript does not catch the input event. Don't understand it. How can I catch input from trigger() with pure JavaScript addEventListener()?

1 Answer 1

1

You can use Element#dispatchEvent to trigger an input event.

document.getElementById('filter-created-at').addEventListener('input', function(e) {
  console.log('Regular input');
});
$('#filter-created-at').on('input', function(e) {
  console.log('jQuery input');
});
document.getElementById('filter-created-at').dispatchEvent(new Event('input', {
  bubbles: true
}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="filter-created-at" />

Sign up to request clarification or add additional context in comments.

5 Comments

This is the only way? No simpler and cleaner solution? It should be simpler.
@Čamo This isn't a difficult solution to use. I don't believe there is any other way.
I hope there is something like element.input() like element.submit().
@Čamo Unfortunately, there is no such method.
Ok thank you it works. But I dont understand why jquery trigger() does not call dispatchEvent()? I expected that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.