0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

f.select選択時に、jQueryを利用して、動的にフォーム要素を表示・非表示させる

Posted at

はじめに

プルダウンの選択した種類によってフォームの表示を変更して行きます。

記述変更箇所

application.scss
view
application.js

scss

.time{ display: none; }

view

<%= f.text_area :sentence %>
    <select name="task[category]" id="task_category">
      <option value="">選択してください</option>
      <option value="時間が決まったタスク">時間が決まったタスク</option>
      <option value="よく使うタスク">よく使うタスク</option>
      <option value="たまたま行ったタスク">たまたま行ったタスク</option>
      <option value="ToDo">ToDo</option>
    </select>
//f.selectをやめデベロッパーからhtmlをコピペ
    <%= f.time_field :time, class: "time" %>
    <%= f.submit %>

application.js

document.addEventListener('DOMContentLoaded', (event) => {
//処理が適用されなかったため追加
  $( "#task_category" ).change(function() {
//select_idを取得しハンドラーで適用
    if (this.value == "時間が決まったタスク"){
//this.valueで#task_categoryのvalueを取得
      $("#task_time").removeClass( "time" );
//idをデベロッパーで確認しremoveClassでcssを削除
    }else{
      $("#task_time").addClass( "time" );
//addClassでcssを追加
    }
  });
});
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?