Hiding a Form and Showing a Form on the Same Page in Rails

Hiding and Showing a Form on the Same Page in Rails

Hiding a Form

Step 1

In the view, make the form remote and define id for the form.

<%= form_for(@article, remote: true, html: { id: 'article_form' }) do |f| %>

Step 2

Define id for cancel button.

<%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'article_cancel_button' %>

Step 3

In the article form partial, attach click handler and prevent event default to hide form.

 <script type='text/javascript'>
    $(function() {
      $(document).on("click", "#article_cancel_button", function(event){

We also show the new article link after the form gets hidden. Note that we are attaching to click event, otherwise this will not work in conjunction with Turbolinks.

Step 4

We need to show the new article link and hide the form after the user submits the form. In create.js.erb:


Showing a Form on the Same Page

Step 1

In the index page, make the link remote: true. Define id for the Add New Article link that will show the form on the same page.

<%= link_to 'Add New Article', 
            id: 'new_article_link', 
            class: 'btn btn-success', 
            remote: true %>

Step 2

When the 'Add New Article' button is clicked we can show the form. In new.js.erb:

$('#new_article_link').hide().after('<%= j render("form") %>');

we hide the link after the form is rendered.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.