Revealing concealed content within a Bootstrap modal

I am seeking a way to utilize bootstrap modal in order to display certain contents. Specifically, the email, gender, and status information should initially be hidden and revealed only upon clicking the "view more" button. My goal is to showcase this data using bootstrap modal.

let table;

const show = (data) => {
  table.innerHTML = data
    .map(({id,name,email, gender,status}) => `<tr>
      <td> ${name}</td>
      <td> <button class="more" data-id="${id}">View More</button></td>
      <td hidden id="email">${email}</td>
      <td hidden id="gender">${gender}</td>
      <td hidden id="status">${status}</td>
      </tr>`)
    .join("");
};

const load = () => {
  fetch("https://gorest.co.in/public/v2/users")
    .then(result => result.json())
    .then(show);
};

window.addEventListener("DOMContentLoaded", () => {
  table = document.getElementById('table');
  table.addEventListener("click", (e) => {
    const tgt = e.target.closest("button");
    if (!tgt) return;
    tgt.closest("tr").querySelectorAll("td").forEach(td => td.hidden = false);
  })

  load();
});

Answer №1

Not specifying the use of Bootstrap 5 in this version. Many code examples are taken from the Bootstrap site.

The approach here involves utilizing a single modal and swapping data instead of creating a modal for each record.

Instead of using a button within the table, the Bootstrap version is used with additional record data stored in data attributes. While this method increases efficiency, a preferable alternative would be to store the data in an object and reference it using data-id.

// show() function
<button type="button"
        class="btn btn-primary more"
        data-bs-toggle="modal"
        data-bs-target="#exampleModal"
        data-id="${id}"
        data-name="${name}"
        data-email="${email}"
        data-gender="${gender}"
        data-status="${status}">
    View More
</button>

Adding the HTML structure of the bootstrap modal

<!-- Modal -->
<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">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div id="modalDynamicContent" class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Lastly, attaching an event listener for show.bs.modal to track when the modal is opened by clicking on any View More button.


const myModalEl = document.getElementById('exampleModal');
const myModalContent = document.getElementById('modalDynamicContent');

myModalEl.addEventListener('show.bs.modal', event => {
    // Button that triggered modal
    viewMoreButton = event.relatedTarget;
    
    // Retrieve data
    id = viewMoreButton.dataset.id;
    email = viewMoreButton.dataset.email;
    gender = viewMoreButton.dataset.gender;
    status = viewMoreButton.dataset.status;

    myModalContent.innerHTML = `
          <p>
            Email: <span id="email">${email}</span>
          </p>
          <p>
            Gender: <span id="gender">${gender}</span>
          </p>
          <p>
            Status: <span id="status">${status}</span>
          </p>
    `
});

let table;
const show = (data) => {
  //console.table(data);
  table.innerHTML = data
    .map(({id,name,email, gender,status}) => `<tr>
      <td> ${name}</td>
      <td>
        <button type="button"
                class="btn btn-primary more"
                data-bs-toggle="modal"
                data-bs-target="#exampleModal"
                data-id="${id}"
                data-name="${name}"
                data-email="${email}"
                data-gender="${gender}"
                data-status="${status}">
          View More
        </button>
      </td>
      <td hidden id="email">${email}</td>
      <td hidden id="gender">${gender}</td>
      <td hidden id="status">${status}</td>
      </tr>`)
    .join("");
};

const load = () => {
  fetch("https://gorest.co.in/public/v2/users")
    .then(result => result.json())
    .then(show);
};
window.addEventListener("DOMContentLoaded", () => {
  table = document.getElementById('table');
  //table.addEventListener("click", (e) => {
    //const tgt = e.target.closest("button");
    //if (!tgt) return;
    //tgt.closest("tr").querySelectorAll("td").forEach(td => td.hidden = false);
  //})
  load();
});

const myModalEl = document.getElementById('exampleModal');
const myModalContent = document.getElementById('modalDynamicContent');

myModalEl.addEventListener('show.bs.modal', event => {
    // Button that triggered modal
    viewMoreButton = event.relatedTarget;

    // Get data
    id = viewMoreButton.dataset.id;
    email = viewMoreButton.dataset.email;
    gender = viewMoreButton.dataset.gender;
    status = viewMoreButton.dataset.status;

    myModalContent.innerHTML = `
          <p>
            Email: <span id="email">${email}</span>
          </p>
          <p>
            Gender: <span id="gender">${gender}</span>
          </p>
          <p>
            Status: <span id="status">${status}</span>
          </p>
    `
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.min.js"></script>
    

<table id='table'>
</table>

<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">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div id="modalDynamicContent" class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

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

Plotly: maintaining consistent color scheme across identical elements in multiple graphs

I am currently utilizing Plotly in Javascript to generate some interactive graphs. My goal is to create 2 pie charts that display the distribution of a sale based on A) units and B) value. While I am able to generate the plots successfully, I have notice ...

Turn off drag and drop functionality and activate selection in HTML

Recently, I encountered a strange issue where selected text became draggable and droppable onto other text, causing it to concatenate. To resolve this problem, I added the following code: ondragstart="return false" onmousedown="return false" However, thi ...

"Explore the capabilities of WebWorks AJAX for seamless cross-domain requests

Currently developing a playbook app using webworks sdk. I am encountering an issue with making an HTTP request (method: post) while sending and receiving data. Although I am able to receive a response from the server, the server does not seem to receive th ...

What is the process for assigning values once the Google Charts program has completed its drawing?

It might sound strange, but I have a piece of code here: let globalResult = []; let defaultData = ["None", 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200]; $(document).ready(() => { // add a listener to the textbox $('#in ...

Unable to shift to the side while in full flexibility mode

I ran into an issue with my code, shown in the image below. I am trying to position 1 on the left and 2 on the right, but something seems off. Can you spot the problem? <div className="mt-5 mx-5 py-3 shadow bg-white"> &l ...

When trying to make a POST request, the browser displayed an error message stating "net::ERR_CONNECTION

Currently, my project involves coding with React.js on the client side and Express.js on the server side. I have encountered an issue when attempting to use the POST method to transmit data from the client to the server for storage in a JSON file. The erro ...

How can I transfer an image from the clipboard onto a fabric.js canvas?

I am currently working on developing a function that will allow users to paste an image from their clipboard onto a canvas as a new fabric.Image(). However, every search result I come across either discusses cloning existing objects within the canvas or pa ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...

Excessive ajax requests occurring when the options in the form are altered

My website contains two main sections: (1) search criteria, which include selection boxes in a form used to access database information, and (2) a div where the results are displayed. The initial page load serializes default values from the form and sends ...

Tips for keeping a Bootstrap Modal in a fixed position on the screen as you scroll

I am facing an issue with a button that is supposed to trigger a Bootstrap Modal. It seems that the modal is not visible when the page has been scrolled down. Upon clicking the button to show the modal, the background darkens as expected, but the modal its ...

Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table. Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I n ...

"Implementing React to dynamically load and update value in component, enabling user interaction with the

As a newcomer to the world of React (16.4.2), I am trying to grasp its functionality without delving into Redux just yet; my focus is solely on understanding the core React library. In my application, there is an input component called RangeInput, which r ...

Using Material-UI's <Autocomplete/> component and the getOptionLabel prop to handle an empty string value

Currently, I am working with material-ui autocomplete and passing an array of states to its options property. However, I have encountered an issue with the getOptionLabel method: Material-UI: The `getOptionLabel` method of Autocomplete returned undefined ...

Benefits of using props destructuring in React - beyond just being a syntactic shortcut

This idea might not be exclusive to React, but I've struggled to discover a compelling reason beyond concise and easier-to-read code. ...

Enable lightbox functionality prior to all images being fully loaded

I have a large number of images (thumbnails) on my website and I am using the Featherlite lightbox plugin. However, when I click on one of the loaded images while they are still loading, the lightbox does not work as expected. Instead of opening in a modal ...

A guide on invoking JQuery functions

Exploring the various methods of applying a JQuery function to a variable has been on my mind lately. For example, I am familiar with this approach: $.DoThis(variable); However, is there a way to invoke it at the end similar to traditional Javascript f ...

Tips on accessing the value of a dynamic field in an ASP ModalPopup

I am having trouble with my modalpopup extender. When the user clicks an 'Add' button, a dynamic textbox is created within the popup. However, I am struggling to get a reference to this textbox in the codebehind. Adding a 'textchanged' ...

I'm having trouble getting my .click method to work with the <div id=menuButton>. Can anyone help me figure out why this is happening?

Here is the HTML code I created for a dropdown menu. Initially, in the CSS file, the menu is set to display: none; <!doctype html> <html> <head> <title>DropDown Menu</title> <link rel="stylesheet" href="normalize ...

Ways to guarantee that a task is completed only after another task has finished

Attempting to avoid duplication as I find myself in the midst of a significant issue. Currently working on a JavaScript codebase consisting of thousands of lines. The specific problem at hand involves: methodA being invoked from within its own class. met ...

Is it possible to transfer an HTML table to a PowerPoint presentation directly from the client

Is there a specific jquery or javascript solution available for converting an HTML table directly into a PowerPoint presentation? So far, the only solution I have come across is html table export, which provides export options for various file formats. H ...