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

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.

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" } %>
Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.