LoginSignup
3
1

More than 5 years have passed since last update.

RailsでjQueryのtoggle,show,hideがうまく動作しなかった

Last updated at Posted at 2018-03-06

やりたいこと

railsでjQueryを書いている時にハマったことについて共有。
やりたいことは、

画面キャプチャ.png
ここの「回答する」ボタンをクリックすると
画面キャプチャ2.png
回答欄が表示される。これをjQueryを使って実現する。

環境

  • Ruby on Rails(5.1.5)
  • Bootstrap(3.3.7)
  • query-rails(4.3.1)
  • ブラウザはSafari(11.0.2)とChrome(64.0.3282.186)

問題のコード

questions/show.html.erb
<h2 align="center">Title <%= @question.title %></h2>

<div class="well col-xs-8 col-xs-offset-2">
  <%= simple_format(@question.description) %>
  <hr>
  <!-- このボタンを押すと -->
  <button type="button" class="hidden-bin">回答する</button> 

</div>

<!--ここを表示をトグルする-->
<div class="hidden" style="display: none">
<%= render 'answers/form' %>
</div>
question.coffee
$(document).on 'turbolinks:load', ->
  $(".hidden-btn").on "click" , ->
    $(".hidden").toggle()

解決策

どうやらBootstrapclass="hidden"と競合していた模様。class名をclass="hidden-formと変えることにより解決。わかっている人にとってはとても当たり前のことかもしれないが、2時間くらい悩みました。 

これを
<div class="hidden" style="display: none">
<%= render 'answers/form' %>
</div>

こうする
<div class="hidden-form" style="display: none"> 
<%= render 'answers/form' %>
</div>
$(document).on 'turbolinks:load', ->
  $(".hidden-btn").on "click" , ->
    $(".hidden-form").toggle()
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1