Search code examples
javascriptcheckboxecmascript-6dispatchevent

Trigger checkbox change event with plain javascript (NOT jQuery)


I'm building a multiple select with ES6. It's all up and functional (moving trough items, clicking them, highlighting, whatever you want) but the only problem is handling those checkboxes. Whenever an item is highlighted and enter is pressed I must catch the event, verify the number of checked items and update dropdown's title.

The methods I found so far are based on using document.createEvent() and fireEvent(), but they both are deprecated (and yes, I can't figgure out how to solve it with CustomEvent).

I've been trying to find an answer for 3 days now, trust me when I say I tried my best.

checkbox.checked = true
checkbox.checked = false

only change checkbox value but won't trigger any event


Solution

  • Since changing a checkbox value doesn't trigger any event, of course it won't trigger neither 'click' nor 'change' event. They must be triggered separately or together on whatever the case, and the listeners must be specific as well, and new Event('change') works just fine. It was a matter of how to trigger and listen the events. Thanks for the answers :-)