Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap hide modal not working in Rails 6 using ajax

I am trying to hide a bootstrap modal in rails 6 via a jquery call but after 2 weeks of trying I can't seem to get it to work...

My modal is setup in a view like this:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#logModal">
  Launch demo modal
</button>

<!-- Modal -->
<%= simple_form_for(@log, remote: true) do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>

<div class="modal fade" id="logModal" tabindex="-1" role="dialog" aria-labelledby="logModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="logModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">


        <div class="form-inputs">
          <%= f.association :user %>
          <%= f.association :project %>
          <%= f.input :body %>
        </div>
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" id="logmodalclose">Close</button>
        <%= submit_tag "create", close: "btn btn-primary" %>
    </div>
  </div>
</div>
</div>
<% end %>

The controller then has format.js added to the create method.

I have then created a file Create.js.erb to the views with the following code in it

$('#logModal').modal('hide');

When I view the webpage the modal loads but doesn't close. If I put an alert before the hide modal line then the alert appears so the routing is obviously loading. If I paste $('#logModal').modal('hide'); into the chrome browsers console I get the following error

Uncaught TypeError: $(...).modal is not a function

looking at other answers this seems to be caused by loading jquery twice or jquery and bootstrap in the wrong order. I have spent a week trying different things and nothing seems to work. I am using rails 6 and the appication.js file in app/javascript/paths reads:

require("jquery")
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("bootstrap/dist/js/bootstrap")

// Tomas added to import Style sheets
import '../stylesheets/application'
import './bootstrap_custom.js'


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

//= require jquery3
//= require popper
//= require bootstrap-sprockets

To be honest I don't understand the difference between Require("Jquery") and //= require jquery I'm fairly new to Rails...

any help much appreciated

UPDATE: It works when I add the following at the bottom of the view

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

However, I think these libraries should be loading via the Application.js... I pressume if I could get it to work this would be a better way of doing it...?

like image 914
Tomas Avatar asked Oct 14 '19 07:10

Tomas


People also ask

How to create a modal in rails using bootstrap?

Creating Rails Modals Using Bootstrap 1 Initial Setup. Add gem 'bootstrap' and gem 'popperjs' to your Gemfile and run bundle install. 2 Modify Layouts in View. Make sure that this view is partial. Inside it, you will have the content you want to show in the modal. 3 Modify Your Controller 4 Enjoy! We have finally reached the end! ...

Does bootstrap require popper or jQuery?

Bootstrap needs both jQuery and Popper.js in order for Javascript to function properly. The big difference between Rails 5 and Rails 6 at this point is that Rails 6 does not require you to add these as gems to your Gemfile. All you need is Yarn and the Webpacker gem (that Rails 6 comes with).

How to open/reopen modal without using bootstrap?

As a workaround you can remove "fade" class from your modal. If you need to prevent user to close the modal on click you need to add data-backdrop="static" attribute to your modal. The below statements show how to open/reopen Modal without using bootstrap. And then use the below jQuery to reopen the modal if it is closed.

When to use Bootstrap 5 in rails?

Bootstrap 5 is highly customisable and delightful when you need to deliver a consistent design as fast as possible. Let's see how to use it with the last Rails version.


1 Answers

This might be a total hack but I was able to resolve this issue by setting jquery to the global object explicitly in application.js.

import jquery from 'jquery';
window.$ = window.jquery = jquery;

application.js:

require("@rails/ujs").start();
require("@rails/activestorage").start();
require("channels");
import jquery from 'jquery';
window.$ = window.jquery = jquery;

import "bootstrap";
import "../stylesheets/application";

environment.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default'] 
  })
)

module.exports = environment
like image 186
ameyab Avatar answered Oct 19 '22 20:10

ameyab