How to use update_page to dynamically add form elements?

I’ve got a form with some upload boxes, and I’d really like to add more
boxes when the user clicks on a link, a la Gmail attachments. I was
thinking I could just use any javascript for this, it’s not hard, but I
had two thoughts:

  1. Rails is gravitating towards less dependency on typing your own
    javascript, for example RJS
  2. I’m not just inserting regular textfields, I’m inserting
    text_field_with_auto_complete, which gets pretty messy if I want to put
    that in a JavaScript function somehow. I want to make this as simple as
    possible.

So here’s what I’ve got at the moment.

<%= link_to_function ‘add another song’,
update_page { |page| page.insert_html :before, ‘album_submit’,
“Name:” + text_field_with_auto_complete(:songs, :name,
:index => 2) +
" " + file_field_tag(‘songs[2][uploaded_data]’) + ‘

} %>

The problem is, I’ve got the number “2” hardcoded in there. I don’t want
to reference “2” here in the index, I want to reference something that
will be incremented every time this is called. Now, if I have it
reference a Ruby value, that doesn’t help me, because this block is
evaluated when the page is loaded, not when the link is clicked.

Ideas:

  1. Reference a JavaScript function somehow. This is kind of naive, as
    both the ID and NAME of the text field will have this index value.
  2. Instead of making this inline, make this true AJAX, and a ruby
    variable can be incremented on the remote side. This is overkill,
    though, there’s no reason why I should be executing anything on the
    server side just to add fields to my form.

I’ve been fighting with this something fierce, so any advice would be
much appreciated.

On Dec 18, 4:37 pm, Liam M. [email protected]
wrote:

I’ve got a form with some upload boxes, and I’d really like to add more
boxes when the user clicks on a link, a la Gmail attachments.
<%= link_to_function ‘add another song’,

“link_to_function” is the right way to do this.

  1. Instead of making this inline, make this true AJAX, and a ruby
    variable can be incremented on the remote side.

Refer to this excellent screencast which does something similar to
what you are trying to do.
http://railscasts.com/episodes/73
You are right. Making a round trip to the server using Ajax is
overkill for adding a form element.

hth
ponnada

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs