gpt4 book ai didi

ruby-on-rails - 如何在 Ruby 中检查默认单选按钮?

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:01 25 4
gpt4 key购买 nike

我有一个使用 Ruby 构建的单选按钮,如下所示

      <p>Which design do you prefer to use? </p>
<% [ 'Design 1', 'Design 2', 'Design 3', 'Design 4', 'Design 5' ].each do |theme| %>
<br><%= radio_button_tag 'theme', theme, @theme == theme %>
<%= label_tag "theme_#{theme}", theme.humanize %>
<% end %>

我想确保默认情况下始终选中第一个元素(也称为设计 1),除非用户选择其他设计。

最佳答案

您可以这样做:传入 checked检查项目

<%= radio_button_tag 'theme', theme, checked: @theme.FIELD_NAME == 'design' %>

详情请看这里http://apidock.com/rails/ActionView/Helpers/FormTagHelper/radio_button_tag

回复您的评论:

Ahmm I dont understand? :( So <%= radio_button_tag 'theme', theme %>
becomes <%= radio_button_tag 'theme', theme, checked: @theme.FIELD_NAME == 'design' %> ?? But this throws an error? I just want the first radio button element to be selected by default –

FIELD_NAME是模型中列的名称。要只检查第一项,您可以尝试这样做:只需添加 checked: true关键词

<%= radio_button_tag 'theme', theme, @theme == theme, checked: true %>

好的,您需要执行以下操作:

<% [ 'Design 1', 'Design 2', 'Design 3', 'Design 4', 'Design 5' ].each_with_index do |theme, i| %>
<% if i == 0 %>
<br><%= radio_button_tag 'theme', theme, @theme == theme, checked: true %>
<% else %>
<br><%= radio_button_tag 'theme', theme, @theme == theme %>
<% end %>
<%= label_tag "theme_#{theme}", theme.humanize %>
<% end %>

关于ruby-on-rails - 如何在 Ruby 中检查默认单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26498539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com