JavaScript not triggering Bootstrap 5 modal popup to appear

I am attempting to open a bootstrap 5 modal programmatically, but when the code runs, nothing happens

My page includes bootstrap.min.js and I have an HTML modal template within the page

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="mb-3">
                                <label for="recipient-name" class="col-form-label">Recipient:</label>
                                <input type="text" class="form-control" id="recipient-name">
                            </div>
                            <div class="mb-3">
                                <label for="message-text" class="col-form-label">Message:</label>
                                <textarea class="form-control" id="message-text"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Send message</button>
                    </div>
                </div>
            </div>
        </div>

This is the javascript I have written to trigger the modal popup

var exampleModalPopup = new bootstrap.Modal(document.getElementById("exampleModal"), {});
            var modalTitle = exampleModalPopup.querySelector('.modal-title');
            var modalBodyInput = exampleModalPopup.querySelector('.modal-body input');
            modalTitle.textContent = 'An error has occurred';
            modalBodyInput.value = 'error';
            exampleModalPopup.modal();

The modal popup object gets created but nothing happens, can someone point out where the issue may be? It's failing at

exampleModalPopup.querySelector('.modal-title');

Answer №1

The issue arises when you try to apply the querySelector() method to a Bootstrap Modal object instead of a DOM object. Instead, consider the following approach...

var exampleModal= document.getElementById("exampleModal");
var exampleModalPopup = new bootstrap.Modal(exampleModal, {});
var modalTitle = exampleModal.querySelector('.modal-title');
var modalBodyInput = exampleModal.querySelector('.modal-body input');
modalTitle.textContent = 'A problem has been detected';
modalBodyInput.value = 'problem';
exampleModalPopup.show();

Codeply

Furthermore, make use of the show() method instead of the non-existent modal() method.

Answer №2

As stated in the documentation, to display the modal using JavaScript, you can use the following code snippet:

var modalExample = new bootstrap.Modal(document.getElementById("exampleModal"), {});
modalExample.show();

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

Attempted to identify whether an item exists in an array, and if it does, then add the item to the array; if not, then perform

Allow me to make some clarifications as it might be a bit confusing initially. This project I'm working on is for school. I don't expect anyone to do it for me, but I need help with a specific part. I'm creating a simple shopping cart using ...

Determine the availability of a distant website through AJAX requests

My website runs PHP's cURL to check the online status of 5 different URLs, however, this process tends to slow down the page load time significantly, especially if one of the sites being checked is not working. Someone suggested using jQuery's a ...

Stagnant variable value after onClick event

After exploring various solutions, none seem to quite fit my needs. I want to update the variable "currentIndex" when a user clicks on an image. Currently, the change occurs within the onClick function but does not affect the outside variable. I am unsur ...

Removing multiple tables simultaneously and encountering an error while utilizing ajax response text

I am facing a couple of challenges. First Issue: I encountered a problem while trying to delete groups from two tables in the database (gmembers and groups). My goal was to check if a user left a group, and if there are no remaining members in that g ...

angular-ui-tab-scroll: Odd spacing between blocks and tabs, each separated individually

Greetings! I would like to express my gratitude for this wonderful library! However, I am encountering an unusual issue when trying to wrap a tabset with tabs that are included separately. This can be done either by adding individual tab elements manually ...

Adding values to a knockout data table without refreshing the page

I am currently experiencing difficulties with refreshing my knockout.js DataTable. I have a data table that loads correctly on page load using the attached function method. I also have multiple buttons (Display All, Allowed, Not Allowed) that display the t ...

Is it Possible to Remove an Item from an Array in Vue without Explicitly Knowing the Array's

I'm currently working on a feature that involves removing an item from an array when it is clicked. The code I have so far looks like this: <span @click="deleteItem(index)" v-for="(item, index) in customTaxonomies.featured" v-html="item"></s ...

When initializing a local scope property as null in Angular.js, it may end up being undefined

Recently, I created a custom Angular directive. <location zipcode="35423" cityname="" statecode=""></location> Within the directive, I defined the following: scope: { zipcode: "@", cityname: "@", ...

Troubleshooting: Else block not functioning as expected within a React JS map function

I have a notification feature that makes an API call every 10 seconds to display an alert based on the response. However, I'm encountering an issue where the div is not being rendered properly. The div should be displayed based on certain conditions w ...

Using JQuery's $.ajax() method to send a post request and pass data to invoke a specific method in

I'm currently in the process of learning JQuery and encountering some challenges with utilizing the $.ajax() function. My goal is to send data to a controller for processing. During my debugging of the JQuery, it seems that the ajax call isn't b ...

In order to develop a JS class in React JS, I must import Scripts

I have a collection of SDK scripts that need to be included in the following manner: <script src="../libs/async.min.js"></script> <script src="../libs/es6-shim.js"></script> <script src="../libs/websdk.client.bundle.min.js ...

Creating a masterpiece on the final piece of paper

As someone who is new to programming with JavaScript and canvas, I have a function called drawLines(canvasIndex, startPosition) that is used to draw lines on a canvas. The function takes in two arguments: canvasIndex, which represents the canvas being draw ...

Creating a responsive HTML, CSS, and JavaScript popup: A step-by-step guide

I'm facing a challenge in making my HTML, CSS, and JavaScript popup responsive. Despite looking into various resources, I haven't been able to find a solution that fits my code. However, I am confident that it is achievable to make it responsive! ...

Updating data in a table upon submission of a form in Rails

In my Rails 3.2 application, I am displaying a table of results using the @jobs variable passed to the view from a SQL query. I want to add a button that will trigger a controller action when clicked. The action should perform some database operations and ...

Display a string variable in a field using JavaScript and JQuery

I am currently coding in JavaScript using JQuery, and I am facing an issue when trying to display the content of variables in a field. Here is my code snippet: function editEvolution(pos, nature, desc, di) { $('#diE').val(di); $(&apo ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

Struggling with inserting JavaScript into the <input type="date"> calendar

Objective: I am trying to automate a calendar on Chrome using Selenium (Python + behave). The problem: Despite attempting to pass a value via JavaScript, the date is only set when physically clicked through the calendar. Keyboard input and JS method do no ...

Transforming jQuery object into HTML code

I need assistance with a JavaScript task where I am trying to parse and replace an item within an HTML string, but then struggling to convert it back to a string. Specifically, I am having difficulty turning the new jQuery object back to HTML. var compile ...

Identifying unique client ids in ASP.NET

This question is somewhat related to Forcing client ids in ASP.NET, but with a unique twist. When working with ASP.NET, clientids are generated based on its internal mechanism. I am interested in running a background xmlhttprequest query to perform update ...

Turn off the incorrect TypeScript error detection

After setting up 'interact.js' using jspm and npm for TypeScript compatibility, I am encountering errors in my code: import { interact } from 'interact.js/interact' // ==> typescript error: TS2307: Cannot find module 'interact. ...