简体   繁体   中英

Rails - how to add an attribute to a text_field_tag

I want to add a data attribute to a text field tag

<%= text_field_tag(:address) %>

which produces

<input id="address" type="text" name="address") %>

to make it have the HTML of

<input id="address" type="text" name="address" data-clob="ccc") %>

so I tried

<%= text_field_tag(:address, data:{clob: 'ccc'}) %>

but it was added as the actual value instead of an attribute, ie

<input id="address" type="text" value="{:data=>{:clob=>"ccc"}}" name="address"></input>

even though for a text field label I had used

<%= label_tag(:address, t("ui.reservations.between_now_and_param", 
param: @start_date.strftime(    time_format)), data:{blob: 'bbb'})%>

as detailed in How to add HTML5 data- attributes to a rails form label tag?

How can I add it as an attribute?

The answer was that a second parameter was required for the value and using "" or ,, didn't work but but using nil did - caused no "value=" attribute to be generated, eg

<%= text_field_tag(:address, nil, data:{clob: 'ccc'}) %>

Though I need to see if that works if this form is redisplayed on error...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM