Is it possible to trigger a Bootstrap 5.2 Popover within an "if" statement?

As part of my input validation process, I am utilizing popovers. However, I am struggling with the syntax to make it work as intended.

https://jsbin.com/sufitelodo/1/edit?html,js,output

The JSBin provided serves as the foundation for this issue.

I am unsure how to code the HTML for a hidden Bootstrap 5.2 popover that only appears when triggered within an if statement. To test this, input 0 into field A and any number into fields B and C. The first error should occur when A equals 0, then change A to a non-zero value; the second error should trigger when submitting with B equaling C. My goal is to replace the alert boxes with popovers.

const popoverTriggerList = [].slice.call(
  document.querySelectorAll('[data-bs-toggle="popover"]')
);
const popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl, { html: true });
});



document.getElementById("button").addEventListener("click", testMe);

function testMe() {
  let inputA = parseFloat(document.getElementById("aInput").value);
  let inputB = parseFloat(document.getElementById("bInput").value);
  let inputC = parseFloat(document.getElementById("cInput").value);
  let popoverTest1 = document.getElementById("popoverTest1");
  let popoverTest2 = document.getElementById("popoverTest2");
  
  if (inputA === 0) {
    // Make popoverTest1 come up here
    //alert("This is when popoverTest1 should fire");
    bootstrap.Popover.getOrCreateInstance('#popoverTest1').show()
    
    return false;
    
  } else if (inputB === inputC) {
    // Make popoverTest2 come up here
    //alert("This is when popoverTest2 should fire");
    bootstrap.Popover.getOrCreateInstance('#popoverTest2').show()
    
    return false;
  }
}

document.getElementById("close1").addEventListener("click", closePop);
function closePop () {
  bootstrap.Popover.getInstance('#popoverTest1').hide();
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cfef3f3e8efe8eefdecdca9b2aeb2af">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<label for="aInput">A Input</label>
  <input type="number" id="aInput">
  <span id="popoverTest1" 
          data-bs-container="body"
          data-bs-toggle="popover" 
          data-bs-trigger="manual" 
          data-bs-content="Top popover"
          data-bs-title='This is zero <a href="" id="close1">x</a>'
          data-bs-content='Change it to something non-zero'>
</span>
  <br><br>
  <label for="bInput">B Input</label>
  <input type="number" id="bInput">
  <span id="popoverTest2" 
          data-bs-container="body" 
          data-bs-toggle="popover" 
          data-bs-trigger="manual" 
          data-bs-content="Top popover"
          data-bs-title="This is the same as Input C"
          data-bs-content="Change it so it's not the same as Input C">
</span>
  <br> <br>
  <label for="cInput">C Input</label>
  <input type="number" id="cInput">
 
<button type="button" class="btn btn-warning" id="button">Hit Me</button>
  
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2825253e393e382b3a0a7f64786479">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7L+jL6+MDMPddm/YxR/OVnSoWDVa" crossorigin="anonymous"></script>

Instead of using alerts, I would like to implement cleaner popovers from Bootstrap. Unfortunately, despite trying to comprehend the documentation, I am still unable to get them functioning properly. Additionally, after the popover displays, it should be able to close upon user action.

I attempted using

data-bs-trigger="focus"
, but this did not allow for proper closing functionality.

Thank you for your assistance in solving this challenge.

*** Edit - I have made updates to the code to simplify usage with Vanilla, however, there seems to be an issue with closing the popover using the designated button... I cannot figure out how to dispose of it.

Answer №1

I made sure to include all the necessary assets as outlined in the documentation for version 5.2:

https://getbootstrap.com/docs/5.2/getting-started/introduction/

Additionally, I followed the provided code snippet to initialize all the popovers:

https://getbootstrap.com/docs/5.2/components/popovers/

I implemented a strategy to retrieve the instance of a popover based on a CSS selector:

const popover1 = bootstrap.Popover.getOrCreateInstance('#popoverTest1');
  

The methods used to display and hide the popovers were:

popover1.show();
  popover1.hide();
  

In addition to your existing logic, I included functionality to hide all popovers when clicking the button before displaying a new one if needed.

I also incorporated a method to handle clicks that would hide any visible popover if one was currently being displayed. This change was necessary due to Bootstrap's reliance on the attribute data-bs-trigger set as focus, which requires user interaction to trigger the popover instead of explicitly calling the .show() method. As we are using .show() to display the popovers, we had to implement the corresponding .hide() functionality, which was achieved through a click event listener on the window object.

Answer №2

To display the appropriate Popover, you must first obtain its instance and then activate it.

function runTest() {
    let valueA = parseFloat(document.getElementById("aInput").value);
    let valueB = parseFloat(document.getElementById("bInput").value);
    let valueC = parseFloat(document.getElementById("cInput").value);
    let popOver1 = document.getElementById("popoverTest1");
    let popOver2 = document.getElementById("popoverTest2");
    
    if (valueA === 0) {
        // Activate popOver1 in this section
        bootstrap.Popover.getOrCreateInstance('#popoverTest1').show()
    }
    else if (valueB === valueC) {
        // Activate popOver2 in this section
        bootstrap.Popover.getOrCreateInstance('#popoverTest2').show()
    }
}

View Demo

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

Incorporating interactive maps into an AngularJS web application

I've been attempting to integrate Google Maps into my AngularJS application, using the script tag below: <script src="https://maps.googleapis.com/maps/api/js?key=[MySecretKeyHere]&callback=initMap" async defer></script> I found this ...

Exploring ways to extract key:value pairs from an encoded URL form using POST in express/node.js

I have a web form with 4 input fields. The form is set up as follows: <form action="/" method="post" onsubmit="alert('data submittet')"> It should default to x-www-form-urlencoded. The form functions correctly and I am able to submit my d ...

Obtaining a state hook value within an imported function in React

In order to access a value from the state hook stored in a special function, it is straightforward to do so in a functional component. For example, this can be achieved in App.js like this: import React from 'react'; import { Switch, Route, with ...

Detect changes in class properties using Node.js

Is it feasible to establish direct proxy watchers for class properties in Node.js? class User{ constructor(name){ this.name = name; let pObject = new Proxy(this,{ set: () => { console.log("something cha ...

Accessing the statusText of a 403 response in Axios (React, Express, Node.js)

Within my component, there is a register function that makes an API call. The API checks if the email already exists and provides an appropriate status and statusText based on the result. Below is the API call handler in my Express app: router.post(' ...

The parameter did not successfully transfer to the internal function within Firebase Cloud Functions

I am currently working on a Firebase cloud function that looks like this: exports.foo = functions.database .ref("/candidates/{jobTrack}/{candidateId}") .onCreate((snap, context) => { const candidate = snap.val().candidate; const jobTrack = ...

Extract information from a Web Service using Javascript

As a novice in web app development, I am currently working on creating a login page and retrieving user data from a local database using JavaScript. Despite my efforts, I seem to have made an error somewhere in my code. Below is the snippet of my JavaScrip ...

What is the best way to dynamically duplicate the Bootstrap multi-select feature?

$(function() { $('#days').multiselect({ includeSelectAllOption: true }); $('#btnSelected').click(function() { var selected = $("#days option:selected"); var message = ""; selected.each(function() { message ...

"Encountered a reference error in Node.js Express due to an undefined

const _expressPackage = require("express"); const _bodyParserPackage = require("body-parser"); const _sqlPackage = require("mssql"); //Initializing the app with the express web framework ...

Is it possible to rearrange the order of rows and columns based on the viewport size?

Is it possible to achieve two different layouts with Bootstrap 5 based on the viewport size? I want to avoid using display:none and JS/Jquery tricks if possible. I attempted to accomplish this by utilizing Bootstrap 5 tools, but encountered issues on lar ...

What is the cause behind the failure of this regular expression in JavaScript?

I have been struggling to make this code display "matched!" for the specific string. I've tried various methods but nothing seems to be working. Here's the HTML part: <div id="ssn">123-45-6789</div> And here's the JavaScript p ...

Retrieving URL from AJAX Request in Express JS

Currently, I am in the process of developing an Express App and encountering a challenge regarding the storage of the user's URL from which their AJAX request originated. In simpler terms, when a website, such as www.example.com, sends an HTTP request ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

"Can you please provide guidance on accessing the current value of Ref in react-native

I have exhausted all options provided in this URL: How to extract values from input types using this.refs in reactjs? From ref.current.value to ref.value to ref._getText(), everything returns as undefined. After inspecting the JSON output of the ref objec ...

How can a row in AG-Grid be updated without causing a refresh?

I am working on adding a custom radio button feature for users to select a row. Currently, I have the following code: const Cell = (cellProps) => { const { data, node, api } = cellProps const selectedRow = () => { let { isChecked } = data ...

Exploring innerHTML in JavaScript for event listening

Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no chang ...

Having trouble setting up discord.js on my device, getting an error message that says "Unable to install discord.js /

Trying to install Discord.JS by using the command npm install discord.js seems to be successful at first, but unfortunately it doesn't work as expected. Upon running the index.js file, an error message pops up indicating that the module discord.js is ...

Node.js Promise Rejection: TypeError - Unable to access property 'sign' because it is undefined

tran_script.js const CoinStack = require('coinstack-sdk-js'); const coinstackClient = new CoinStack('YOUR_COINSTACK_ACCESS_KEY', 'YOUR_COINSTACK_SECRET_KEY'); // Actual keys not displayed const privateKeyWIF = CoinStack.ECK ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...