Using stimulus imported modules in .js.erb views

Hi there,

I’m currently in the process of converting our vanilla js to stimulus controllers. I have a select dropdown on which I have attached select2. Everything is working fine except one thing. When trying to change the value of the dropdown in a .js.erb view like this $("#new_order_sender").val("<%= %>").trigger('change.select2'); it doesn’t trigger the change nor does it change the value. It seems to me that select2 is not available globally in the browser and that is causing the issue but I’m not 100% sure. Anyone had the same problem or something similar?

Without seeing how your HTML is set up, what you probably want to do is have one Stimulus controller that listens for change event in the first select, then fetchs the new html for the second select, and then triggers your select2.

I have a small tutorial I’d written up about chaining together multiple select statements that may help you out. It isn’t exactly the same, but it has two select fields that load different filtered data lists depending on what is picked. I think it will give you a good starting point to organize your own code.