提交表单后如何设置单选按钮的值? [英] How to set the value of radio button after submitting form?
问题描述
我使用的是 Rails 3.2.我有一个搜索表单,其下方有单选按钮.它根据选择的单选按钮进行搜索.目前我认为这一点:
I'm using Rails 3.2. I have a search form that has radio buttons below it. It searches based on which of the radio buttons are selected. Currently I have this in my view:
= radio_button_tag(:ad_type, "free")
= label_tag(:ad_type_free, "free")
= radio_button_tag(:ad_type, "paid")
= label_tag(:ad_type_paid, "paid")
= radio_button_tag(:ad_type, "featured")
= label_tag(:ad_type_featured, "featured")
所以我的问题是,如何设置要选择的默认单选按钮?我曾尝试使用 radio_button_tag(:ad_type, "free", :checked => true)
,但在提交表单后,它总是选择该单选按钮.我想要的是根据之前的请求选择值.我应该从 url 参数中获取值吗?如果是这样,我如何设置初始默认值(当没有以前的搜索时)?非常感谢.
So my question is this, how do I set the default radio button to be selected? I have tried using radio_button_tag(:ad_type, "free", :checked => true)
, but after submitting the form, it always selects that radio button. What I want is to select the value based on the previous request. Should I get the value from the url params? If so, how do I set the initial default value(when there are no previous searches)? Thanks a lot.
更新
我创建了一个辅助方法 ad_type_selected?
I've created a helper method ad_type_selected?
def ad_type_selected?(ad_type)
selected_ad_type = params[:ad_type] || "free"
(selected_ad_type == ad_type) ? true : false
end
我认为:
= radio_button_tag(:ad_type, "free", :checked => ad_type_selected?("free"))
但是,单选按钮仍然没有被选中.检查日志,我看到对帮助程序的第一次调用返回 true,其他调用返回 false,这正是我想要的.但问题是它仍然没有选择单选按钮.如果我检查input标签,我只能看到checked属性设置为checked".
However, the radio button still doesn't get selected. Checking the logs, I see that the first call to the helper returns true, and the others false, which is what I want. But problem is it still doesn't select the radio button. If I check the input tag, I can only see that the checked attribute is set to "checked".
推荐答案
显然,为所有单选按钮添加一个选中的属性会导致最后一个单选按钮始终被选中.所以我所做的就是在参数与单选按钮匹配时添加一个检查属性.
Apparently, adding a checked attribute for all the radio buttons causes the last radio button to be always selected. So what I did is to just add a checked attribute if the params matched the radio button.
所以在我的例子中,我只是使用了一个助手来生成合适的单选按钮,如下所示:
So for my example, I just used a helper to generate the appropriate radio button like so:
def ad_type_radio_button(ad_type)
selected_ad_type = params[:ad_type] || "free"
if selected_ad_type == ad_type
radio_button_tag(:ad_type, ad_type, :checked => true)
else
radio_button_tag(:ad_type, ad_type)
end
end
在我看来:
= ad_type_radio_button("free")
我知道它远非优雅,但现在它的行为是正确的.
I know it's far from elegant, but it behaves correctly now.
这篇关于提交表单后如何设置单选按钮的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!