【Rails】セレクトボックスにdisabledを適用する方法
やりたいこと
@choices = ["選択肢1", "選択肢2", "選択肢3"]
<%= select_tag :choice, options_for_select(@choices) %>
このようにセレクトボックスを実装しており、選択できないデフォルトの項目を先頭に表示したい。
結論
@choices = ["選択肢1", "選択肢2", "選択肢3"]@choices = ["値を選択してください", "選択肢1", "選択肢2", "選択肢3"]
まずdisable
なラベルとして表示する値を配列の先頭に格納。
<%= select_tag :choice, options_for_select(@choices) %><%= select_tag :choice, options_for_select(@choices, selected: choices[0], disabled: choices[0]) %>
そしてその追加した項目を、selected
とdisabled
に指定してあげればOK。これで選択できないデフォルトの項目を先頭に表示できた。
<%= form.select :choice, @choices, selected: choices[0], disabled: choices[0] %>
ちなみにform_for
下の場合はこのようにすれば大丈夫だった。
よくありがちなミス
ケース1
@choices = ["値を選択してください", "選択肢1", "選択肢2", "選択肢3"]@choices = ["選択肢1", "選択肢2", "選択肢3"]
<%= select_tag :choice, options_for_select(@choices, selected: choices[0], disabled: choices[0]) %><%= select_tag :choice, options_for_select(@choices, selected: "値を選択してください", disabled: "値を選択してください") %>
このようにselected
・disable
に文字列を直接指定することはできない。あくまで配列の要素として指定する必要がある。
ケース2
<%= select_tag :choice, options_for_select(@choices), selected: @choices[0], disabled: @choices[0] %>
また、options_for_select
ではなくselect_tag
のdisable
に指定しまうと、セレクトボックス自体が無効になってしまう。
参考