twbs / bootstrap

The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
https://getbootstrap.com
MIT License
170.08k stars 78.78k forks source link

Uncaught TypeError: $(...).modal is not a function #40847

Open nongtan7898 opened 1 day ago

nongtan7898 commented 1 day ago

Prerequisites

Describe the issue

I am having trouble closing the modal using jquery.

vite vue jquery bootstrap 5.3

<template>
  <!-- Button trigger modal -->
  <button
    type="button"
    class="btn btn-primary"
    data-bs-toggle="modal"
    data-bs-target="#exampleModal"
  >
    Launch demo modal
  </button>

  <!-- 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 class="modal-body">...</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" @click="close()">Save changes</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
const close = () => {
  window.$('#exampleModal').modal('toggle')
}
</script>

<style></style>

Reduced test cases

What operating system(s) are you seeing the problem on?

Windows

What browser(s) are you seeing the problem on?

Chrome

What version of Bootstrap are you using?

v5.3.3

github-actions[bot] commented 1 day ago

Hello @nongtan7898. Bug reports must include a live demo of the issue. Per our contributing guidelines, please create a reduced test case on CodePen or StackBlitz and report back with your link, Bootstrap version, and specific browser and Operating System details.

nongtan7898 commented 1 day ago

this Reduced test cases https://stackblitz.com/edit/vitejs-vite-lp48zk?file=src%2Fmain.js

julien-deramond commented 9 hours ago

I'd say that you need to get access to the instance of the modal. I'm not that familiar with Vue.js, but you could try to add this to the main.js:

import * as bootstrap from 'bootstrap';
window.bootstrap = bootstrap;

And then, in App.vue, something like:

const close = () => {
  const modalInstance = bootstrap.Modal.getOrCreateInstance('#exampleModal');
  modalInstance.hide();
};