How do you pass dynamic data into a Bootstrap modal when triggered? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you pass dynamic data into a Bootstrap modal when triggered?

message-square
0

To pass dynamic data into a Bootstrap modal when it is triggered (whether via a button/link with data-* attributes or programmatically in JavaScript/jQuery), listen to Bootstrap’s show.bs.modal event on the modal element, read event.relatedTarget (the trigger element that opened the modal, when triggered by a DOM element) or read from an explicit data store/Map, validate and populate the modal’s text/inputs/attributes inside a try / catch block, and clean up stale state on hidden.bs.modal.


1. Passing Trigger Data via data-* Attributes and show.bs.modal

Attach data-* attributes on trigger buttons/links, listen for show.bs.modal, inspect event.relatedTarget, and populate the modal’s target fields safely:

// Populate a Bootstrap modal dynamically when opened via a `data-*` trigger element
function bindDynamicBootstrapModal(modalSelector, fieldMap) {
  if (typeof modalSelector !== "string" || modalSelector.trim().length === 0) {
    throw new TypeError("Expected modalSelector to be a non-empty CSS selector string.");
  }
  if (!(fieldMap instanceof Map) || fieldMap.size === 0) {
    throw new TypeError("Expected fieldMap to be a non-empty Map of dataKey -> targetSelector.");
  }
  if (typeof document === "undefined") {
    throw new Error("DOM document is unavailable.");
  }

  const modalEl = document.querySelector(modalSelector);
  if (!(modalEl instanceof Element)) {
    throw new Error(`No modal element found for selector "${modalSelector}".`);
  }

  const handleShow = (event) => {
    try {
      const triggerEl = event.relatedTarget;
      if (!(triggerEl instanceof Element)) {
        return;
      }

      for (const [dataKey, targetSelector] of fieldMap.entries()) {
        if (typeof dataKey !== "string" || typeof targetSelector !== "string") {
          continue;
        }

        const targetEl = modalEl.querySelector(targetSelector);
        if (!(targetEl instanceof Element)) {
          continue;
        }

        const rawValue = triggerEl.dataset[dataKey] ?? "";

        if (
          targetEl instanceof HTMLInputElement ||
          targetEl instanceof HTMLTextAreaElement ||
          targetEl instanceof HTMLSelectElement
        ) {
          targetEl.value = rawValue;
        } else {
          targetEl.textContent = rawValue;
        }
      }
    } catch (error) {
      console.error(`Failed populating Bootstrap modal "${modalSelector}": ${error.message}`);
    }
  };

  const handleHidden = () => {
    try {
      for (const [, targetSelector] of fieldMap.entries()) {
        const targetEl = modalEl.querySelector(targetSelector);
        if (!targetEl) {
          continue;
        }
        if (
          targetEl instanceof HTMLInputElement ||
          targetEl instanceof HTMLTextAreaElement ||
          targetEl instanceof HTMLSelectElement
        ) {
          targetEl.value = "";
        } else {
          targetEl.textContent = "";
        }
      }
    } catch (error) {
      console.error(`Failed clearing Bootstrap modal "${modalSelector}": ${error.message}`);
    }
  };

  modalEl.addEventListener("show.bs.modal", handleShow);
  modalEl.addEventListener("hidden.bs.modal", handleHidden);

  return () => {
    modalEl.removeEventListener("show.bs.modal", handleShow);
    modalEl.removeEventListener("hidden.bs.modal", handleHidden);
  };
}

// Example usage:
// HTML trigger:
// <button type="button" data-bs-toggle="modal" data-bs-target="#editModal" data-item-id="42" data-item-title="Invoice #42">Edit</button>
//
// JS binding:
// const cleanupModal = bindDynamicBootstrapModal("#editModal", new Map([
//   ["itemId", 'input[name="itemId"]'],
//   ["itemTitle", ".modal-title"]
// ]));
  • Use show.bs.modal rather than shown.bs.modal: show.bs.modal fires before the modal finishes sliding/fading into view, avoiding visible flicker as fields populate.
  • Avoid innerHTML for untrusted data-* strings: Use .textContent or form control .value so HTML strings render as safe text rather than executable markup.

2. Passing Complex Objects or Programmatic Payloads via a Map Store

When you need to pass structured objects, arrays, or non-string values (or trigger the modal programmatically without a clicked DOM button), store payloads keyed by ID in a Map and open the modal via Bootstrap’s modal API:

// Store complex record payloads by ID and open a Bootstrap modal programmatically
function openModalWithPayload(modalEl, recordStore, recordId, renderPayload) {
  if (!(modalEl instanceof Element)) {
    throw new TypeError("Expected modalEl to be a DOM Element.");
  }
  if (!(recordStore instanceof Map)) {
    throw new TypeError("Expected recordStore to be a Map instance.");
  }
  if (typeof renderPayload !== "function") {
    throw new TypeError("Expected renderPayload to be a callback function.");
  }
  if (typeof bootstrap === "undefined" || !bootstrap.Modal) {
    throw new Error("Bootstrap Modal API is not available on window/global scope.");
  }

  try {
    if (!recordStore.has(recordId)) {
      throw new RangeError(`No record found in store for key "${String(recordId)}".`);
    }

    const payload = recordStore.get(recordId);
    renderPayload(modalEl, payload);

    const modalInstance = bootstrap.Modal.getOrCreateInstance(modalEl);
    modalInstance.show();
    return modalInstance;
  } catch (error) {
    throw new Error(`Unable to open modal with payload: ${error.message}`);
  }
}

// Example usage:
// const recordsById = new Map([
//   ["ord-101", { id: "ord-101", customer: "Tariq", total: 145.5 }]
// ]);
// const modalNode = document.querySelector("#orderModal");
// openModalWithPayload(modalNode, recordsById, "ord-101", (el, data) => {
//   const titleEl = el.querySelector(".modal-title");
//   if (titleEl) titleEl.textContent = `Order ${data.id} —${data.customer}`;
// });
  • Use bootstrap.Modal.getOrCreateInstance(modalEl) (Bootstrap 5+): Prevents creating duplicate modal backdrop instances when opening the same modal repeatedly.
  • Keep data-* attributes camelCased in JS (data-user-role -> dataset.userRole): Dataset converts kebab-case attribute names to camelCase automatically.

3. Bootstrap Version, Event Delegation, and Cleanup Gotchas

Watch out for version differences and dynamic DOM lists (such as AJAX-rendered tables or rows):

  • Bootstrap 5 uses data-bs-toggle / data-bs-target and native show.bs.modal events; Bootstrap 4 uses data-toggle / data-target: Mismatched data attributes prevent the modal from opening when clicking triggers.
  • event.relatedTarget is null when .show() is called programmatically: Always guard if (!(triggerEl instanceof Element)) inside show.bs.modal so programmatic opens do not fail.
  • Resetting state on hidden.bs.modal avoids stale values: Clearing inputs and labels when hidden prevents leftover data from appearing if a subsequent open path omits a field.