Tips for automatically closing a bootstrap modal popup when there is no data available in the dialog

Using a bootstrap model here, each card in the model has a close button. Clicking on the close button will hide or remove the card from the model popup. If there is only one card left in the popup and I want to close that last card, I also want the model popup to automatically close. However, I am unable to achieve this on my own. Can someone please help?

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
      .modal-body{
        height: 70vh;
    overflow-y: auto;
      }
  </style>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container">
  
  <!-- Button to Open the Modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

  /* The rest of the HTML code remains unchanged */

</div>


<script>


$(document).ready(function(){
    $('.clscurrent').on('click', function() {
     $(this).closest('.removeit').remove();
});
});
</script>
</body>
</html>

Answer №1

Here is a neat little trick:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
      .modal-body{
        height: 70vh;
    overflow-y: auto;
      }
  </style>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c6e6363787f787e6d7c4c38223a223d">[email protected]</a>/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a607b7f6f78734a39243c243a">[email protected]</a>/dist/jquery.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afdfc0dfdfcadd81c5dcef9e819e99819e">[email protected]</a>/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a3835352e292e283b2a1a6e746c746b">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container">
  
  <!-- Button to Open the Modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
  </button>

  <!-- The Modal -->
  <div class="modal" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">
      
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Modal Heading</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        
        <!-- Modal body -->
        <div class="modal-body">
         <div class="card removeit mb-2">
            
            <div class="card-header"><span>Title</span></div>
            <div class="card-body">
                <p>Card body 1</p>

            </div>
            <div class="card-footer">
                <button class="btn btn-primary float-right clscurrent ml-2 ">Done</button>
                <button class="btn btn-danger float-right clscurrent">Skip</button>
            </div>
         </div>

         <div class="card removeit mb-2">
            <div class="card-header"><span>Title</span></div>
            <div class="card-body">
                <p>Card body 2</p>

            </div>
            <div class="card-footer">
                <button class="btn btn-primary float-right clscurrent ml-2">Done</button>
                <button class="btn btn-danger float-right clscurrent">Skip</button>
            </div>
         </div>

         <!-- More card elements omitted for brevity -->

         
        </div>
        
        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
        </div>
        
      </div>
    </div>
  </div>
  
</div>


<script>


$(document).ready(function(){
    $('.clscurrent').on('click', function() {
     $(this).closest('.removeit').remove();
      if($("#myModal").find('div.card').length==0)
        {
          $("#myModal").modal('hide');
        }
    });
});


</script>
</body>
</html>

Answer №2

In case your modal length is not accessible or falls below one, you can utilize the following code:

$('#modal_name').modal('hide')

This jQuery code effectively hides the modal. We trust this information proves beneficial to you.

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

Ways to automatically display the date upon loading the view

I have integrated a plugin with Angular, which is essentially an extension. Upon loading the view, only an empty input is visible. Clicking on the input reveals a calendar with today's date displayed. My objective is to automatically load today&apos ...

Exploring the transparency of material lab autocomplete drop-down text for enabling multiple selections

Check out this demo for checkboxes and tags in Material UI The code below demonstrates an autocomplete component that functions correctly. However, the drop-down text appears transparent. Is there a way to fix this issue without modifying any libraries? ...

the method of utilizing JavaScript to showcase an HTML form

I have created a form for entering an employee's skills. Below the form, there is a link to add a new skill. When this link is clicked, the form should be displayed again. My code looks like this: <html> <head> ...

Is Asp.net 4 resetting the array with every new run?

I have developed a basic asp.net web page to generate HTML content. The concept is to store previous user inputs in an array each time they click a button, and display them along with the most recent input. However, I encountered an issue where the array a ...

What methods does Google use to catalogue web pages that load dynamically through jQuery?

Similar Query: Does Google crawl AJAX content? In my forum, the URLs follow a specific format for course pages such as COURSE PAGE - http://www.example.com/course/course-feed/course_id/1 Each course page contains numerous questions, with each questio ...

Constructing a Primeng MessageService causes a blank webpage to appear

After downloading the QuickStart CLI of PrimeNG for Angular, I added a second component for a chart that was already included in the UI components. Everything seemed to be set up correctly, but when I saved, I ended up with a completely blank page for the ...

Ways to expand the constructor function of the THREE.Mesh class

Exploring Three.js, I'm working on creating a basic model of the solar system. My current task involves building constructor functions for planets and moons. However, I keep encountering an error message: The function setShadow() is not recognized. ...

In order to properly execute the JavaScript code, it is essential to create a highly customized HTML layout from the ER

I am currently utilizing this resource to create a gallery of images on my Rails page. Here is the HTML code required to display the images: <a href="assets/gallery/ave.jpg" title="Ave" data-gallery> <img src="assets/gallery/ave_tb.jpg" alt="Av ...

Uploading several files using Cordova

Recently, I have been developing a project utilizing Cordova Phonegap to create a Windows Phone application. I am facing the challenge of uploading multiple files to a server using a single request, alongside other form data. My question is, is it possibl ...

What is the CSS method for altering the color of a slider's runnable track upon selection?

Seeking assistance in changing the slider track color upon selection. Struggling to achieve the desired outcome of altering the color as it slides. CSS: /* Custom Styles */ .text-size-slider { line-height: 100%; font-size: 14px; position: relative ...

Step-by-step guide on creating a draggable navigation bar:

I am encountering an issue creating a droppable menu. I am currently working on Menu 1 but struggling to figure out how to make the drop-down menus appear on the right side. <link href='http://fonts.googleapis.com/css?family=Oswald:300,400' r ...

Head and tail tally

I've been working on coding a heads or tails system in JavaScript, but I've hit a roadblock. I am struggling to find a solution. Here is what I have so far: const userInput = prompt("Heads or Tails?"); const arr = [0, 0, 1, 1, 1, 0, 1, 0, 1]; ...

The email message content is not displaying correctly

I'm in the process of merging multiple HTML tables into a single $message, which will then be passed to the email body as shown below. // Sending the email if(smtp_mail($To,$cc, $Subject, $message, $headers)) { echo "Email Sent"; } else { echo "An ...

Ways to view the outcome of json_encode function?

In PHP, I have an array that looks like this: $user_data = Array ( [session_id] => 30a6cf574ebbdb11154ff134f6ccf4ea [ip_address] => 127.0.0.1 [user_agent] => Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1 [las ...

Solving issues with Angular4 Router changes

I'm attempting to chain the router resolver for my application. Below are my Router options: { path: '', component: AdminComponent, resolve: [ SessionResolve, LocaleResolve ] } The desired flow is to first call S ...

issue encountered when attempting to use string.replace with regex

When using a regex like this: I am attempting to replace "subdir" with a custom string using the string.replace method. However, when I use myStr.replace(/^.*\/\/.*\.net\/.*\/(.*)\/.*\z/, otherStr) The result is not as ...

Pulling JavaScript - referencing an external script

I am currently facing a challenging dilemma that requires a simple yet intricate solution. My objective is to develop a script capable of playing chess on my behalf, utilizing an engine to determine the optimal moves for pieces such as rooks, bishops, king ...

How does the interaction between Express and Angular for routing in the MEAN Stack function?

Currently, I am utilizing Express static to direct to the public directory. //app.js app.use(express.static( __dirname + '/public')); I am looking for a way to have most of the UI routing done by AngularJS. However, it seems that it only works ...

JavaScript Flash player for iPad

As many of us know, the iPad does not support Flash. However, I am curious if the iPad sends any specific error messages that can be captured using Javascript. I realize one method is to detect the iPad from the user agent string, but I am interested in w ...

Styling in CSS is being applied to a button element within a React component,

Having trouble with a button styled with the className 'actions' The button displays the CSS styling from '.actions', but not '.actions button'. Both should be applied. This code snippet works for all elements ...