简体   繁体   中英

How to submit two forms with one submit button with rails and javascript

I need to allow a user to type up a comment and submit before asking them to provide account details. Once these details are provided, they are used to create a new user and the comment they wrote is also submitted and belongs to this new user. Currently, I simply can't figure out how to trigger the submit action on both forms, passing all the information to the server to carry these tasks out.

Basically what I want:

  • User writes up a comment, submits
  • Submit button displays a contact info form
  • User fills this out, submits
  • Data from both forms are submitted

What I have:

_feedback.html.erb

  <%= simple_form_for [@post, Comment.new] do |f| %>
      <%= f.input :body, :label => false, :input_html => { :maxlength => '500', :rows => '4', :placeholder => '...'}  %>
      <% if current_user.guest != true %>
        <%= f.button :submit, "Submit" %>
      <% end %>
  <% end %>
  <% if current_user.guest == true %>
    <input type="submit" value="Submit" onclick="contactDisplay()"></input>
  <% end %>

show.html.erb

<% if current_user.guest == true %>
  <div id="contact" class="post-contact">
    <%= simple_form_for(@user, :html => { :multipart => true }, defaults: { label: false, required: true }) do |f| %>
      <%= f.input :name, :input_html => { :placeholder => 'Your Name', :id => 'name'} %>
      <%= f.input :email, :input_html => { :placeholder => 'Your Email', :id => 'email'} %>
    <% end %>
    <input type="submit" value="Submit" onclick="submitContact()"></input>
  </div>
<% end %>
<%= render 'posts/show/feedback' %>

posts.js

function contactDisplay(){
var contact = document.getElementById('contact'); 
    contact.style.display='block';
}

function submitContact(){
    document.getElementById("new_comment").submit();
    document.getElementById("new_user").submit();
}

您可以使用嵌套形式:)这是有关如何实现的方法http://railscasts.com/episodes/196-nested-model-form-part-1

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