Created
May 30, 2021 17:28
-
-
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)
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
<%= 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 %> |
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 { 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