简体   繁体   中英

Create and remove a form_tag with JavaScript in Ruby on Rails

I'm trying to figure out how to add form_tag s to my page dynamically with JavaScript. I can probably figure out how to add regular forms, but I would prefer adding form_tags so I can get the handy "authenticity_token" when the form is submitted. Here is my view...

show.html.erb:

<button id="add-new-form">Add invite</button>

<div class="invite-user-forms">
 <%= form_tag("/contests/#{@contest.id}", remote: true, class: "invite-user", controller: "contestants", action: "create", method: "post") do %>
    <%= text_field_tag(:emailVal) %>
    <%= submit_tag("Send invitation") %>
    <%= button_tag("Remove") %>
  <% end %>
</div>

And here is my outline for my JavaScript expectation, though I don't know how to add a form_tag... application.js:

$(document).ready(function(){
  $("#add-new-form").click(function(){
    $(".invite-user-forms").append("form_tag??");
  });
});

Furthermore, I'd like to remove the form_tag by clicking the "Remove" button_tag ...I assume each new form would need a unique ID in order for this to work, though...so perhaps my JavaScript would look like this?

$(document).ready(function(){
  $("#remove-button-(some unique value)").click(function(){
    $("#unique-form-value").remove();
  });
});

Any advice is gladly appreciated.

To point you in the right direction:

<%= form_for Contestants.new, remote: true do |f| %>
<%= f.button :submit, "create new contestant" %>
<% end %>

And below, you need to loop through all the forms that have been created.

<%= @contestants.each do %>
    <div class="invite-user-forms">
         <%= form_tag("/contests/#{@contest.id}", remote: true, class: "invite-user", controller: "contestants", action: "create", method: "post") do %>
        <%= text_field_tag(:emailVal) %>
        <%= submit_tag("Send invitation") %>
        <%= button_tag("Remove"), remote: true, method: :delete %>
      <% end %>
    </div>
<% end %>

However, right now - you're not actually creating a new contestant, it has already been created, when you hit the button above - Also, when creating an entry it can't be empty (It can't be just a submit button, like I showed you above, so preferably you could put something in a <%= f.hidden_field). Right now, you're editing a contestant, so this form needs to be under the edit action. This form also needs 'remote: true'

If you're uncertain about the workings of remote: true and Ajax with rails, just google 'remote: true rails' and suck up any information you can get your hands on - there's loads.

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