Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I listen for dropdown changes in a collection_select field using Stimulus?

Nicolás Kruk asked in Rails

I found this issue on SO which pretty much is my issue:
https://stackoverflow.com/questions/63964037/cant-make-stimulus-js-data-action-in-collection-select-rails-6

But I can't make that solution work.

In my _form partial I have something like:

<div data-controller="forms">  
    <div class="form-group">
      <%= form.label :product_type %>
      <%= form.collection_select :product_type, Product.product_types.keys, :to_s, :titlecase, data: {action: "change->forms#handleChange"} %>
    </div>
    ...
    </div>
  </div>

And in my Forms Stimulus Controller I have:

export default class extends Controller {
  initialize() {
    console.log("Stimulus at your service!")
  }

  connect() {
    console.log("connected to forms controller");
  }

  handleChange() {
    console.log("the dropdown changed");
  }
}

The initiliaze and connect logs work fine. I get nothing when I change the values of the dropdown though.

Reply

Found the issue. The options passed should be an empty object. Nil will return an error so finally:

<%= form.collection_select :product_type, Product.product_types.keys, :to_s, :titlecase, {}, data: { action: "change->forms#handleChange" } %>
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 81,842+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.