简体   繁体   中英

Render form partial on click, Rails

I can't seem to figure this out, and I've tried multiple forums. I would like to render a form when I click a link using javascript. Could someone show a basic example on how to do this?

Just to clarify @Luan Nico answer since you just have to render a form without doing anything extra in your controller you would be better served if you put your form inside a div tag and then toggle that div to show when you click on button .

Fix:

a. Make a div and put your form inside it

<div id="myForm">
  <%= render "your_form" %>
</div>

b. Hide that div by css

#myform {
  display:none;
}

c. Create your link to show your from :

<%= link_to "Your button","#", id: "yourButton" %>

d. Write your js inside assets/javascript/application.js or make a new file and then require in inside application.js

$(document).on("click","#yourButton",function(){
  $(#myform).show();
});

Assuming the form doesn't change when the button is clicked, just have it's visibility toggled, you can put the entire form inside a div, give it an id, and then you can use jquery:

$('#my-button').click(function (){
  $('#div-id').toggle();
});

Where my-button is the id of the button in HTML, and div-id is the div id in the HTML (something like <button id="my-button">Click me</button> and <div id="div-id"><!-- form --></div> ). Or you can do it with plain JS as well, if you don't have jquery (getElementById, etc).

If the form changes slightly, you can also use this technique, but you will need to add some conditions. Otherwise, you will have to use AJAX to get the current data.

Just a warning, try to avoid passing the whole form HTML via an ajax call, the best way is to provide just the data via json and using JS to populate the HTML with the data.

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