LoginSignup
27
17

More than 5 years have passed since last update.

text_field_tagの書き方

Last updated at Posted at 2018-04-25

text_field_tagを書くときに、ちょっとつまずいた部分をメモします。
※以下slimで書いています。

valueにidやclassの値が入ってしまう場合

起こったこと

sample.html.slim
= text_field_tag 'datetime_interview[start_time]', class: 'time start', placeholder: "開始時間"

と書くと、
text_field_tagスクリーンショット.png
とinputのvalueにソースコードが入ってしまいます。

原因

ここでRailsのリファレンスを確認すると、

 text_field_tag(要素名 [, 値, オプション])

text_field_tagは2つ目の引数は、値(value)となるので、class: 'time start', placeholder: "開始時間"がvalueに入ってしまいます。
※なぜplaceholder: "開始時間"までvalueに含まれるのか分かる方がいらっしゃればご教授願います。

対策

sample.html.slim
= text_field_tag 'datetime_interview[start_time2]', '', class: 'time start', placeholder: "開始時間"

2つ目の引数に、空を入れることで解決します。

「data-hogehoge」などの属性を追加したい場合

起こったこと

sample.html.slim
= text_field_tag 'datetime_interview[start_time2]', '', class: 'time start', placeholder: "開始時間", data-time-format: "H:i"

「data-time-format」(timepickerにおける時刻のフォーマットを定義する属性)を追加したいのですが、syntaxエラーとなります。

原因

キーにハイフンやスペースなどが含まれていたり、数字で始まる場合はsyntaxエラーとなるようです。(コメントありがとうございます)

対策

sample.html.slim
= text_field_tag 'datetime_interview[start_time2]', '', class: 'time start', placeholder: "開始時間", 'data-time-format': "H:i"

「data-time-format」をコーテーションで囲むとうまくいきます。

text_field_tagについて、ちょっとでもあれ?と思ったところがあれば、随時追記したいと思います。

27
17
2

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
27
17