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){
        event.preventDefault();
        $("#article_form").slideUp("slow");
        $('#new_article_link').slideDown("slow");
      })
    })
  </script> 

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:

$('#new_article_link').show();
$('#article_form').hide();

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', 
            new_article_path, 
            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


Create your own user feedback survey