views:

2886

answers:

2

How do I attach an onclick event to a link_to_function such that clicking on the event refreshes an element on the page (using partials)?

When the user clicks the generated link, I'd like to refresh the partial containing the code so that i gets updated.

 def add_step_link(form_builder)
    logger.info 'ADD_STEP_LINK'
    link_to_function 'add a step' do |page|
      form_builder.fields_for :steps, Step.new, :child_index => 'NEW_RECORD' do |f|
        logger.info 'inserted js'
        html = render(:partial => 'step', :locals => { :step_form => f, :i=>@i+=1})
        page << "$('steps').insert({ bottom: '#{escape_javascript(html)}'.replace(/NEW_RECORD/g, new Date().getTime()) });"
      end
    end
  end

I have a partial in a larger form that contains just:

<%= add_step_link(technique_form) %>

I am attempting keeping track of the number of steps in a technique. In the form I am creating, users can add new steps to a set of instructions. Right now, I have default fields for steps 1-7. Adding one step, gets you step 8. The problem is that subsequent steps are numbered '8' also.

I am extending the "Multiple child models in a dynamic form" tutorial in http://railsforum.com/viewtopic.php?id=28447 for my own purposes.

+5  A: 

Ok, I'm a little confused by what you are doing, but I'm going to try and make some suggestions.

Rather than use link_to_function, use link_to_remote. Link to function calls javascript, but what you actally want to do is call back to a controller that then runs some rjs to either replace the full partial, or more likely, append the new partial (containing the step) to the end of your current steps.

This is similar to all those examples you will have seen where people append a comment to the end of their blog comments (expect using link_to_remote rather than remote_form_for) see 3/4 of the way through http://media.rubyonrails.org/video/rails_blog_2.mov

You can see the docs for link_to_remote here: http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html

RichH
I am pretty sure link_to_remote is what you need. You make a remote call to the server, returning HTML (or Javascript) that you can inject into the page.
Toby Hede
A: 

I suggest using link_to_remote as RichH suggests. The trick for you it seems is keeping track of @i. I'd either put it as a URL parameter in link_to_remote, or in the session object. I'd suggest the session—it seems easier.

zenazn