adding form elements via a js / ajax call

I want to have a link in certain areas of my form that will say [+add] and that will dynamically add a form element to that area. For instance, if there are 2 text_fields, and user wants 3.

I know that there are some hide/unhide options , though I’m not sure how that works, however I think if there’s a way to add them would be better .

Any suggestions ?

Stuart

I’m running into an error that I’m unsure of how to proceed with: So in the form I’ve added a link_to_remote

<%= link_to_remote “[+]”, :update => ‘xtratitle’,

:url => {:action => “add_title_field”} %>

The action: def add_title_field render(:partial => ‘txtfield’) end

The partial: <%= text_field(:canlocation, :city, “index” => 1)%>

So all I really want to do is add a text field into the form. Maybe link_to_remote is the wrong call. I’m getting an error :

ActiveRecord::RecordNotFound

in CanpositionsController#add_title_field

Couldn't find Candidate without an ID

It looks like (this is a restful controller) that it’s hitting my before_filter to find the candidate id.

Any ideas ?

TIA Stuart

I’m running into an error that I’m unsure of how to proceed with: So in the form I’ve added a link_to_remote

<%= link_to_remote “[+]”, :update => ‘xtratitle’,

:url => {:action => “add_title_field”} %>

The action: def add_title_field render(:partial => ‘txtfield’) end

The partial: <%= text_field(:canlocation, :city, “index” => 1)%>

I got this to work, but odd that it only works once? In other words it won’t continue to generate text_fields.

Guess I’ll have to add another partial ?

Stuart

Ok so you don't need an ajax call for this it is overkill. All you really need is some javascript to add a new form element. So here is a js function that will insert a new text_field when you click a link.

<script type='text/javascript'> function addNewTextField(id, obj, meth, val){    new Insertion.Before(id, '<input type="text" name="'+obj+'['+meth+']" value="'+val+'" />') } </script>

<% form_for(:whatever, :url => whateverss_path) do |f| %> <%= text_filed 'whatever', 'foo' %>

<%= link_to_function "[+] add", "addNewTextField('buttons_info', 'canlocation', 'city')" %>

   <div class="buttons_info">        <%= submit_tag "Submit" %>     </div> <% end %>

  Have fun with it.

-- Ezra Zygmuntowicz-- Lead Rails Evangelist -- ez@engineyard.com -- Engine Yard, Serious Rails Hosting -- (866) 518-YARD (9273)