Skip to content

Instantly share code, notes, and snippets.

@SafeAF
Forked from dalezak/_form.html.erb
Created April 1, 2023 16:27
Show Gist options
  • Save SafeAF/926062f74f45519d95ca41d7b049ac7d to your computer and use it in GitHub Desktop.
Save SafeAF/926062f74f45519d95ca41d7b049ac7d to your computer and use it in GitHub Desktop.
Stimulus.js Toggle Controller to show and hide form elements based on select value
<div class="form-group">
<%= form.label :type, "Type", class: "font-weight-bold" %>
<%= form.select :type, ['TextQuestion', 'UrlQuestion'], { include_blank: true }, { class: "form-control", data: { action: "input->toggle#changed", target: "toggle.select" } } %>
</div>
<div class="form-group">
<%= form.label :name, "Name", class: "font-weight-bold" %>
<%= form.text_field :name, class: "form-control" %>
</div>
<div class="form-group" data-target="toggle.element" data-values="UrlQuestion">
<%= form.label :url, "URL", class: "font-weight-bold" %>
<%= form.text_field :url, class: "form-control" %>
</div>
import ApplicationController from './application_controller'
export default class extends ApplicationController {
static targets = ["element", "select"]
connect() {
if (this.hasSelectTarget) {
this.toggle(this.elementTarget, this.elementTarget.dataset.values, this.selectTarget.value);
}
if (this.hasSelectTargets) {
for (let select of this.selectTargets) {
this.toggle(this.elementTarget, this.elementTarget.dataset.values, select.value);
}
}
}
changed(event) {
if (this.hasElementTarget) {
this.toggle(this.elementTarget, this.elementTarget.dataset.values, event.target.value);
}
if (this.hasElementTargets) {
for (let element of this.elementTargets) {
this.toggle(element, element.dataset.values, event.target.value);
}
}
}
toggle(element, values, value) {
if (element && values) {
let hidden = true;
for (let _value of values.split(",")) {
if (_value === value) {
hidden = false;
}
}
element.hidden = hidden;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment