获取复选框,如果布尔值为false,则呈现为选中 [英] Get checkbox to render as checked if boolean value is false
问题描述
我有一个在用户设置中工作的表单,用于显示或隐藏用户个人资料的一部分。形式是 check_box_tag
,当它被点击时,我使用jQuery提交表单。这一切都很好。单击复选框可将布尔值从 true
切换为 false
,反之亦然。但是,我想复选框显示为选中如果我的布尔值是 false
。
I have a form working in my User's settings for showing or hiding a part of a User's profile. The form is a check_box_tag
and when it is clicked, I use jQuery to submit the form. This is all working well. Clicking the checkbox toggles the boolean value from true
to false
or vice versa. However, I'd like the checkbox to show as checked if the value of my boolean is false
. How do I do that given my code below?
我的控制器动作到配置文件的 update_attribute
:
My controller action to update_attribute
of the Profile:
def edit_show_hometown_settings
@profile = current_user.profile
if @profile.show_hometown == true
if @profile.update_attributes(:show_hometown => false)
redirect_to settings_path
else
redirect_to settings_path, :notice => 'Oops, something went wrong. Please try again.'
end
elsif @profile.show_hometown == false
if @profile.update_attributes(:show_hometown => true)
redirect_to settings_path
else
redirect_to settings_path, :notice => 'Oops, something went wrong. Please try again.'
end
end
end
形式:
<%= form_tag({:action => "edit_show_hometown_settings", :controller => "profiles"}, :html => {:multipart => true }) do %>
<%= check_box_tag :show_hometown %>
<%= @user.profile.hometown %>
<% end %>
我使用jQuery提交表单:
The jQuery I'm using to submit the form:
$(function(){
$(':checkbox').live('click',function() {
$(this).closest('form').submit();
});
});
推荐答案
我对你的逻辑很困惑,猜猜你得到的想法。只需根据需要改变true和false即可。如果@ user.profile.hometown设置为false,则将此复选框设置为选中。
I am kind of confused about your logic, but I guess you get the idea. Just change true and false as you need them. This will set the checkbox to checked, if @user.profile.hometown is set to false.
<%= check_box_tag :show_hometown , 1 , @user.profile.hometown ? false : true %>
这篇关于获取复选框,如果布尔值为false,则呈现为选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!