Unable to Close Modal with Selectize in Rails 6

During my journey to update an old Go Rails video tutorial for selectize functionality to work with Rails 6, I encountered a challenge.

I have established a relationship where each item belongs to a series.

class Item < ApplicationRecord
belongs_to :series
end

A series, on the other hand, can have many items associated with it.

class Series < ApplicationRecord
has_many :items
end

In the item form, I am utilizing selectize for finding or creating a series.

<%= form_for @item do |form| %>
        <div class="form-group">
            <%= form.select :series_id, Series.all.pluck(:name, :id), {}, { class: "selectize" } %>
        </div>
....

All seemed well until I hit an issue while trying to close the modal after creating a new series. The console threw an error that prevented the modal from closing.

<!-- Modal -->
<div class="modal fade series-modal" id="series-modal" tabindex="-1" role="dialog" aria-labelledby="SeriesModal" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="SeriesModal">Add series</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <%= form_for Series.new do |f| %>
          <div class="form-group">
            <%= f.label :name %>
            <%= f.text_field :name, class: "form-control" %>
          </div>
          <div class="form-group">
            <%= f.collection_select(:account_id, Account.all, :id, :name ) %>
          </div>
      </div>
      <div class="modal-footer">
        <div class="form-group">
            <%= f.submit class: "btn btn-primary" %>
          </div>
        <% end %>
      </div>
    </div>
  </div>
</div>

The JavaScript involved in handling the modal and form interactions is as follows:

<!-- JS -->
$(document).on("turbolinks:load", function() {
    var selectizeCallback = null;

    $(".series-modal").on("hide.bs.modal", function(e) {
        if (selectizeCallback != null) {
            selectizeCallback();
            selectizeCallback = null;
        }

        $("#new_series").trigger("reset");
        $.rails.enableFormElements($("#new_series"));
    });

    $("#new_series").on("submit", function(e) {
        e.preventDefault();
        $.ajax({
            method: "POST",
            url: $(this).attr("action"),
            data: $(this).serialize(),
            success: function(response) {
                selectizeCallback({value: response.id, text: response.name});
                $(".series-modal").modal('toggle');
            }
        });
    });

    $(".selectize").selectize({
        create: function(input, callback) {
            selectizeCallback = callback;

            $(".series-modal").modal();
            $("#series_name").val(input);
        }
    });
});

It seems like there might be a glitch in my JavaScript code related to how Bootstrap handles the closure of modals now.

Your assistance in resolving this matter would be greatly appreciated.

Answer №1

Upon further investigation, I discovered that this pertained to the positioning of the code within the webpage.

It is important to ensure that modal 1 appears before modal 2 in the HTML structure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using an array of objects to set a background image in a Bootstrap carousel using jQuery: a step-by-step guide

I have an array of items, each containing a background property with a URL to an image. Here is my array: https://i.sstatic.net/jfrV0.png Here is the HTML structure: <div id="myCarousel" class="carousel slide" data-ride="carousel"> <ol ...

How can I use HTML to display a new image next to the base image when I hover over it, showing both images side by side?

Looking for assistance with creating a comic webpage containing 2 cartoons. I want the dialog or mind-thought of each cartoon to appear on the page when a user hovers over them. Anyone able to offer some help with this? ...

My iPad is acting up and the .click() function seems to be malfunctioning, but only within

Currently dealing with a perplexing and frustrating issue - I've implemented a .click() event in a view of my backbone.js application (my first time doing so), and while it works perfectly in all desktop browsers, it simply refuses to work on the iPad ...

Tips for incrementing a number by 1 at random intervals using jQuery

Is there a way to increase a number by 1 after an unpredictable delay? For instance, starting with a base value of 10, can we have it change by 1 after a random amount of time (e.g. between 1 and 5 seconds)? I attempted the following code: var ...

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...

Tasks should be defined prior to being referenced in order to avoid any issues

Utilizing multiple files with gulp@4, the main gulpfile.js includes all other files within the ./tasks/ directory. We have implemented the npm gulp-hub package to incorporate multiple gulpfiles within the ./tasks/ directory. However, upon calling the tasks ...

assigning the browser's width to a variable within an scss file

Is there a way to dynamically set the browser's width as a variable? I am familiar with @media queries, but I need to calculate the browser's width for a specific purpose. I attempted using jQuery to achieve this, and it works well with a fixed ...

Showing or hiding child content based on the selected state of a radio button

This is a follow-up question from a previous one on changing check boxes to radio buttons. Now, I need to display child radio buttons and change the background color when the parent radio button is active. The child radio buttons should be hidden and the b ...

What is the best way to sort through an array using JavaScript?

Here's an array for you: values = ["10%", 1000, "5%", 2000] I'm looking to split this into two separate arrays like so: percentages = ["10%","5%"] numbers = [1000,2000] How can I achieve this using JavaSc ...

Equivalent of window.onkeypress in Typescript and NodeJS

Can someone help me figure out how to accomplish the following: document.addEventListener('keypress', (event) => { // Need this function to trigger whenever a key is pressed }); in a node.js environment using TypeScript or JavaScript? ...

Sorting a collection of objects into separate arrays

When working with React, here is an example of the state configuration I am using: state = { Producers: [], France: [], Spain: [], Germany: [], Portugal: [], Greece: [], Austria: [], isLoading: false }; I ...

Tips for creating a unified user interface framework for various web applications sharing a consistent design

Struggling to create a user interface framework for multiple web applications, I'm faced with the challenge of setting up the infrastructure in our unique situation: We have 7 (or more) different web applications built using asp.net mvc Some of thes ...

Javascript Callback function not working as expected

I'm attempting to include an anonymous callback function in my code. I know it might seem a bit messy. By typing into the intro section, it triggers the animation using the .typed method with specific parameters. What I'm struggling to do is imp ...

The reason behind the creation of .pnp.loader.mjs and .pnp.cjs files by yarn

While working on my React project with Vite, I noticed that when using yarn to start the "live server," two new files are created: .pnp.loader.mjs and .pnp.cjs. Can anyone explain what these files are for? I've never come across them before as I usual ...

The multi update feature is only compatible with $ operators when performing bulk find and update operations in node.js, as indicated by the Mongo

Why am I receiving the error message MongoError: multi update only works with $ operators when attempting to update multiple documents using the bulk find and update method. Things I have tried: var bulk = db.collection('users').initialize ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

Update the text inside a paragraph using jQuery

When attempting to modify two values within a paragraph using jQuery, I encountered an issue where only one value was successfully updated, leaving the other empty. <div class="container"> <p class="lead custom_bg" id="comment"> updateme! ...

Looking for assistance with $.ajax - How can I send an object with key-value pairs?

I want to utilize $.ajax to send data in this manner: $.ajax({'url': 'my.php', 'type': 'POST', 'data': arr, 'success': function(response) { alert(res ...

Adding to object in an external JSON file using javascript

I am working with an external file called file.json which contains the following values: { "number": "value" } My goal is to run a function that will append new data to the existing file instead of overwriting it. For instance, after running the func ...