What is the best way to generate a specified number of rows with 3 columns in each row using jquery?

After spending 3 hours trying to create a boostrap 'card' with 3 identical cards per row, I unfortunately failed. Here is the code I attempted:

$.getJSON("./listings.php", function(e) { 
    $.each(e, function(i, e){
        if (e.id != "") {
            //create table here

            var html = '<div class="card-deck mb-3 text-center">'; // this opens the row

            //here are the three columns
            html += '<div class="card mb-4 box-shadow" style="background-image:url(./'+e.img+');background-size:330px; auto;background-repeat:no-repeat; background-position:center;">';
            html += '<div class="card-header" style="background-color: #5bc0de;">';
            html += '<h4 class="my-0 font-weight-normal">'+e.status+'</h4>';
            html += '</div>';
            html += '<div class="card-body">';
            html += '<h1 class="card-title pricing-card-title">&nbsp; </h1>';
            html += '<ul class="list-unstyled mt-3 mb-4">';
            for(var i=0; i<6; i++){
                html += '<li>&nbsp; </li>';
            }
            html += '</ul>';
            html += '<button type="button" id="'+e.id+'" class="community btn btn-block btn-outline-primary">Visit Platform</button>';
            html += '</div>';
            html += '</div>';
            //end of 3rd column

            html += '</div>'; //this closes the row
            $('.community_listing').append(html); //this is just an empty div to host the rows
        }
    })
});

Sad face.

Answer №1

To ensure that your cards are displayed according to the device width and remain responsive, you can set the wrapper as flex.

If you prefer to strictly show 3 cards per row, please let me know so I can adjust my answer accordingly.

//$.getJSON("./listings.php", function(e) { 
var data = [{id:1, img:"", status:1}, {id:2, img:"", status:2}, {id:3, img:"", status:1}, {id:4, img:"", status:3}, {id:5, img:"", status:1}];
    $.each(data, function(i, e){
        if (e.id != "") {
            //create table here

            var html = '<div class="card-deck mb-3 text-center">'; 

            //three columns of the card
            html += '<div class="card mb-4 box-shadow" style="background-image:url(./'+e.img+');background-size:330px; auto;background-repeat:no-repeat; background-position:center;">';
            html += '<div class="card-header" style="background-color: #5bc0de;">';
            html += '<h4 class="my-0 font-weight-normal">'+e.status+'</h4>';
            html += '</div>';
            html += '<div class="card-body">';
            html += '<h1 class="card-title pricing-card-title">&nbsp; </h1>';
            html += '<ul class="list-unstyled mt-3 mb-4">';
            for(let j=0; j<6; j++) {
                html += '<li>&nbsp; </li>';
            }
            html += '<button type="button" id="'+e.id+'" class="community btn btn-block btn-outline-primary">Visit Platform</button>';
            html += '</ul>';
            html += '</div>';
            html += '</div>';

            html += '</div>'; 
            $('.community_listing').append(html); 
        }
    })
//});
.community_listing {
    display: flex;
    flex-wrap: wrap;
}

.card-deck{
    width: 300px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<div class="community_listing"></div>

If you want to see a working fiddle, click here.

Answer №2

I believe I have grasped the essence of your query now. Your aim is to ensure that the cards maintain uniform height, which is why you opted for card-decks.

In the provided example, I have replaced the variable "data" for testing purposes and temporarily disabled the JSON query. Hopefully, this alteration proves beneficial to you.

var targetContainer = $('.community_listing');

//$.getJSON("./listings.php", function(data) {
  var data = [{id:1, img:"", status:1}, {id:2, img:"", status:2}, {id:3, img:"", status:1}, {id:4, img:"", status:3}, {id:5, img:"", status:1}];
  var html = '',
    dataLength = data.length,
    rowClosed = false;

  // Are there truly elements with an empty id?
  data = data.filter(function(i, e) {
    return e.id != "";
  });

  $.each(data, function(i, e) {
    rowClosed = false;

    // Check every third element using modulo and initiate a new row
    if (i % 3 == 0) {
      html += '<div class="card-deck text-center">'; //this opens the row
    }

    // Content for each of the three columns
    html += '<div class="card mb-4 box-shadow" style="background-image:url(./' + e.img + '); background-size: 330px auto; background-repeat: no-repeat; background-position: center;">';
    html += '<div class="card-header" style="background-color: #5bc0de;">';
    html += '<h4 class="my-0 font-weight-normal">' + e.status + '</h4>';
    html += '</div>';
    html += '<div class="card-body">';
    html += '<h1 class="card-title pricing-card-title">&nbsp; </h1>';
    html += '<ul class="list-unstyled mt-3 mb-4">';
    html += '<li>&nbsp; </li>';
    html += '<li>&nbsp; </li>';
    html += '<li>&nbsp; </li>';
    html += '<li>&nbsp; </li>';
    html += '<li>&nbsp; </li>';
    html += '<li>&nbsp; </li>';
    html += '<li>&nbsp; </li>';
    html += '</ul>';
    html += '<button type="button" id="' + e.id + '" class="community btn btn-block btn-outline-primary">Visit Platform</button>';
    html += '</div>';
    html += '</div>';

    // Check modulo for every third element and close the current row
    if (i != 0 && i % 3 == 2) {
      html += '</div>'; //this closes the row
      rowClosed = true;
    }
  });

  // Close the last row if it contains only two elements
  if (!rowClosed) {
    html += '</div>'; // this closes the row
  }

  targetContainer.append(html); // An empty div to contain the rows
//});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<div class="community_listing"></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

The sticky HTML table header feature is functional, however, the header's border disappears while scrolling

Utilizing the react-bootstrap-table2 library in my React project, I added custom CSS to create a sticky top row effect: .table-container { overflow-y: auto; max-height: 500px; } .react-bootstrap-table th { position: sticky; top: -1px; background- ...

Do I have to cram all the content onto a single page just to use a scroll effect?

I'm currently facing a dilemma as I work on building my portfolio. My goal is to primarily use html5 and css3, along with a bit of js, jquery, and other tools if necessary. Although I am not an expert in web development, I wanted to push myself to cre ...

Unable to generate a fresh database entry through form submission

I have designed User and Pairings models as shown below: class User < ActiveRecord::Base enum role: [:student, :supervisor, :admin] has_many :students, class_name: "User", foreign_key: "supervisor_id" belongs_to :supervisor, ...

Exploring the Depths of HTML with Jquery

This is an example of HTML code I am working with: <tr> <td> <div><span id="temp" /> </div> </td> </tr> <tr> <td> <div><span id="temp" /> </di ...

Conceal content within a bullet point

I'm encountering an issue with this specific element. HTML <div class="navbar slide-menu"> <div class="container"> <ul class="nav navbar-default"> <li class="brand"><a href="#">Menu</a></li> ...

What is the best way in jQuery to pass an event to a parent anchor if necessary?

I'm working on a project in ClojureScript using jQuery, and I believe the answer should be applicable to both ClojureScript and JavaScript. My issue involves a helper function that creates an anchor element and then places an icon element inside it. ...

The jQuery Validation plugin ensures that a minimum of one image has been uploaded

My current setup includes a form that permits users to upload images. Each image uploaded by the user is shown in a div named imgHolder, located outside the form. In addition, once a user uploads 5 files, the corresponding file[] input from the form is rem ...

I'm having trouble getting the second controller to function properly in my AngularJS application

I've been looking everywhere for a solution on how to implement two controllers, but I can't seem to get it working. Could there be something wrong with my HTML or could the issue lie in my script? Here is the JavaScript code: <script> v ...

Looking to turn off animation for a WordPress theme element?

Is there a code that I can insert into the style.css file to deactivate the theme animations on my WordPress page? As users scroll down, each element either drops in or slides in. I recently purchased the WP Alchemy theme from , but the animation speed is ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

What causes the position: sticky; property to fail in React implementations?

Currently, I am facing a challenge in making two sidebars sticky so that they will follow as the user scrolls until they reach the bottom of the page. In my current editing project, this implementation seems to be more complex compared to other programs w ...

Ways to troubleshoot JavaScript following an AJAX request?

My webpage is structured into three separate files. The index.html file contains a navigation bar, a content box, and a footer within 3 divs. Additionally, there are two other .html files with different content that should load upon clicking specific links ...

What is the preferred choice: using camelCase in CSS with Styled Components or Emotion for standard React development?

When I'm coding with React Native, I use the styled properties that follow most of CSS syntax and are formatted in camel case. For instance: //... <Component style={styles.container} /> //... const styles = StyleSheet.Create({ ...

In search of a comprehensive demonstration of how to use JQuery/Ajax for pinging with success and failure detection

Given that the process is asynchronous with multiple requests happening in parallel, I would like a solution that can handle these requests and identify which success/failure corresponds to each specific request. I am considering utilizing the jqXHR Object ...

Error: Incompatibility between JSON array and JSON object types

I'm encountering an error and I'm not sure if I can simply change my JSONObject to a JSONArray. The scenario is that I am downloading some JSON data to retrieve a value (under the column friends) which requires me to trigger a second URL to down ...

Printing a modified div element that was created using jQuery on an ASP.NET MVC webpage after the initial page has finished loading

In my view, there is a div that holds multiple tables generated based on the model. Each row in these tables contains fields that can be edited using TextBoxFor. Through jQuery, rows can be moved between tables and new tables can be created dynamically wit ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

How to customize Material UI Autocomplete options background color

Is there a way to change the background color of the dropdown options in my Material UI Autocomplete component? I've checked out some resources, but they only explain how to use the renderOption prop to modify the option text itself, resulting in a a ...

Using an Ajax call with Spring MVC may result in receiving plain text instead of JSON

This is the AJAX call that I am using: $.ajax({ url: 'configuration/activePlatform/', type: 'GET', dataType: 'json', contentType: "application/json", success: function(data){ ...

Transforming an AJAX call into a reusable function

My goal is to simplify my ajax calls by creating a function that can be reused. Although I'm unsure if I'm doing it correctly, I would like to attempt this approach. <script> $(document).ready(function(){ var reg_no=$("#reg_no").va ...