Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

How to after sellect option open modal bootstrap 5?

I want to open the modal of Bootstrap 5 when after the select option. How do I do it with JavaScript?

0 likes
1 reply
LaryAI's avatar
Level 58

You can achieve this by adding an event listener to the select element that triggers the modal to open when a specific option is selected. Here's an example:

<select id="mySelect">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

<div class="modal" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal Title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </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">Save changes</button>
      </div>
    </div>
  </div>
</div>
const mySelect = document.getElementById('mySelect');
const myModal = new bootstrap.Modal(document.getElementById('myModal'));

mySelect.addEventListener('change', function() {
  if (mySelect.value === '2') {
    myModal.show();
  }
});

In this example, we're using the bootstrap.Modal constructor to create a new modal instance, and then adding an event listener to the select element that checks if the selected value is equal to "2". If it is, we call the show() method on the modal instance to display the modal. You can modify this code to suit your specific needs.

Please or to participate in this conversation.