Skip to content

Instantly share code, notes, and snippets.

@yshmarov
Created May 30, 2021 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yshmarov/a910f4949ae28fbba082cb4168b9404d to your computer and use it in GitHub Desktop.
Save yshmarov/a910f4949ae28fbba082cb4168b9404d to your computer and use it in GitHub Desktop.
show or hide div based on a form value (d-none is a bootstrap5 class for hiding)
<%= form_with(model: post) do |form| %>
<%= content_tag :div, nil, data: { controller: "showhide", showhide_show_if_value: "lorem", showhide_hide_class: "d-none" } do %>
<%= form.select :content, [nil, "lorem", "150"], {}, {data: { showhide_target: "field", action: "change->showhide#change" }} %>
<div data-showhide-target="output">
you can see this text if selected value = lorem
</div>
<% end %>
<% end %>
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "field", "output" ]
static classes = [ "hide" ]
static values = {
showIf: String,
}
connect() {
this.change()
}
change() {
if (this.fieldTarget.value != this.showIfValue) {
this.outputTarget.classList.add(this.hideClass)
} else {
this.outputTarget.classList.remove(this.hideClass)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment