-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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