Topic: dynamically add fields to a form through select


I have a problem similar to that proposed in the popular Rayan Bates Railcasts episodes 197 (nested model form part 2).
I have a 3 nested models, a Survey that have many Questions which in turn have many answers.

Now the problem is, I want to put a select menu with the number of questions that I can have, and dynamically add or delete the  fields for the questions and it's corresponding answers. For example the behavior must be: I want a Survey with three Questions and each question with at least one answer, then I choose the 3 option from the select menu, then the page add the necessary three fields for the question and for the answers.

I try to do this with an observe_field but i can't show the fields

if anyone has any advice, it would be very useful

Last edited by zclimber (2011-02-02 17:32:22)

Re: dynamically add fields to a form through select

Any time you're updating multiple page elements , think RJS

So you will need to add an :onchange handler to your select menu that fires off an AJAX request

then in that AJAX request,  you do a render :update

def changed_selection
   if params[:selected] = '1'
      render :update do |page|
         page[:questions].replace_html  '<ul><li>Who played Lumpy in Leave it to Beaver?</li></ul>'
         page[:answers].replace_html  '<ul><li>James Cagney</li><li>Seth Rogan</li><li>None of the above</li></ul>'

This assumes:

Your page has implemented a pull down menu in a div like this:

<div id="questions" >
     <li>I have no questions</li>

<div id="answers">
     <li>So there are no answers</li>
Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.