Topic: SOLVED How to collect dynamically the values of a series of checkboxes

I am trying to build an autocomplete on a textfield, but the autocompleted values returned are dependant from the status of several checkboxes on the page.
I can't figure out how to do that.

Let me explain in more details:
I have a recipe, with several recipes_ingredients in database. There are actions attached to ingredients independently of the recipe, for instance if the ingredient is "carrot", there are actions attached to it such as "peel", "cut into slices" etc… An action can have more than one ingredient: for ingredients oil,vinegar,salt,pepper, you can have the action "mix together".

In my form I have built an autocomplete field for the "action" text field:
          <%= text_field :ingredient_action , :name, :size => 80 -%>
          <div class="auto_complete" id="ingredient_action_name_auto_complete"></div>
          <%= auto_complete_field(:ingredient_action_name,
                                          :frequency => 0.5,
                                          :url => {:action => 'auto_complete_ingredient_action',
                                          :method => :get }) %>

The problem is that the ingredient_action name depends on the list of recipes_ingredients the user has checked in the form e.g.  if the recipe contains ingredients: carrots, tomatoes, potatoes, the user wants only the actions for carrots, he checks carrots but not tomatoes and potatoes. How to pass the information that "carrots" is checked but "tomatoes" and potatoes" aren't to the autocomplete action?
I thought at some point about storing the checked values in a session variable, and adding an observe_field on each checkbox. The problem is that the observe_field doesn't work on check boxes, probably because a check_box tag creates two input types with the same name in the html page generated:

Here are my check_boxes:

          <% for @recipes_ingredient in @recipes_ingredients %>
             <%= check_box "recipes_ingredient[]", 'ingredient_id',{ :checked => 'unchecked'},
                                                                                                          "#{@recipes_ingredient.ingredient_id}" %>
             <%= %><br />
                <% end %>

just FYI the html generated for a checkbox is:
<input name="recipes_ingredient[3][ingredient_id]" type="hidden" value="0" />
<input id="recipes_ingredient_3_ingredient_id" name="recipes_ingredient[3][ingredient_id]" type="checkbox" value="2923" />

Last edited by carrot06 (2012-10-10 07:56:20)

Re: SOLVED How to collect dynamically the values of a series of checkboxes

I solved this by myself:
1) I used an observe_form tag to collect all the values of the check_boxes.
2) it calls a function which sets a session variable with all the values collected
3) then I don't have to bother about passing these values to the autocomplete function. It's available everywhere as a session variable.