简体   繁体   中英

Rails ajax insert additional form fields into form

I am trying to add a new select fields to my form through the built in rails ajax methods but not really sure how to proceed. I've looked at other ajax rails SO but if there is a more relevant one that somebody has found that offers direction, that would be helpful.

details.html.erb

<%= form_for @event, url: wizard_path do |f| %>
# lots of forms here

    <div id="add-field">

    </div>
    <%= link_to "Add Event Detail", add_event_detail_path, remote: true %>

    <%= f.submit "Next" %>
<% end %>

events/build_controller added this

def add_event_detail
    respond_to do |format|
        format.js
    end
end

add_event_detail.erb

$("#add-field").append("<%= f.select(:event_detail, options_for_select([['Option1', 'Option1']) %> <%= f.text_field :event_detail %> ");

I also added this route for now

match "/add_event_detail" => "events/build#add_event_detail", via: 'get'

I have a few issues (besides the bad code that you might see). How do you pass the f variable into the jquery append method and what would be a good way to deal with unique name's for each newly created form essentially, :event_detail1 :event_detail2 etc. Ideally I would want to link that name to the selection in the form

eg :location for the option :location

have you tried to look at nested_form gem ie( https://github.com/ncri/nested_form_fields ), it can dynamically add fields to a form. or try to look at RailsCasts #403 Dynamic Forms it will give ua clear direction. Hope this helps u to the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM