Reputation: 37
I'm new to Stimulus JS. I'm a little stuck trying to make a simple event fire using collection_select
in a form (created with rails g scaffold).
Here's my dropdown-controller.js
(stimulus) file:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["target"];
handleChange() {
console.log('works!')
}
}
Here's my _forms.html.erb
file:
<%= form_with(model: stock_order, local: true) do |form| %>
...
<section data-controller="dropdown">
<div class="field">
<%= form.label :company_id %>
<%= form.collection_select :company_id, Company.all, :id, :name, data: {action: "change->dropdown#handleChange"} %>
</div>
</section>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
I've tried many things:
<%= form.collection_select :company_id, Company.all, :id, :name, data: {action: "change->dropdown#handleChange"} %>
<%= form.collection_select :company_id, Company.all, :id, :name, {data: {action: "change->dropdown#handleChange"}} %>
<%= form.collection_select :company_id, Company.all, :id, :name, data: {action: "dropdown#handleChange"} %>
...etc
I can only get to fire the console.log('works!)
if I use html select tags instead of rails' collection_select
. The event fires if I create a test button or if I use form.check_box
instead.
Any ideas? Sorry if it's a stupid question, I'm out of ideas.
Thanks!
Upvotes: 1
Views: 5015
Reputation: 1568
The data-
are html attributes, so you miss one parameter in form.collection_select
call
<%= form.collection_select :company_id, Company.all, :id, :name, nil, data: {action: "change->dropdown#handleChange"} %>
Upvotes: 2