Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get checkbox to render as checked if boolean value is 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?

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

My form:

<%= form_tag({:action => "edit_show_hometown_settings", :controller => "profiles"}, :html => {:multipart => true }) do %>
  <%= check_box_tag :show_hometown %>
  <%= @user.profile.hometown %>
<% end %>

The jQuery I'm using to submit the form:

$(function(){
    $(':checkbox').live('click',function() {
        $(this).closest('form').submit();
    });
});
like image 873
tvalent2 Avatar asked Jan 13 '12 05:01

tvalent2


1 Answers

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 %>
like image 66
Kristian Hildebrandt Avatar answered Sep 28 '22 08:09

Kristian Hildebrandt