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

Ways to eliminate existing information when conducting a search

Recently, I was tasked with integrating a search engine into a website that already has a list of data displayed on the first page. The challenge I faced was figuring out how to hide or remove this existing data when a new search request is made. You can v ...

Performing a jQuery ajax request on data that has been dynamically loaded using

I am currently in the process of constructing a form for users to make reservations on a website. I have successfully set it up so that when a user selects a shift, the available dates are populated. Now, my goal is to have the available seats load when a ...

jq: filter out arrays that include element B and include element A

My information consists of JSON arrays. Each array includes elements with both name and ID keys: [ { "name": "first_source", "id": "abcdef" }, { "name": "second_source", "id": "ghijkl" }, { "name": "third_source", "id": " ...

The jquery methods might encounter an issue with an undefined object

I have been attempting to implement a function that triggers when the user reaches the bottom of the window, but TypeScript is flagging errors and mentioning potential undefined objects related to window.scrollTop(), height(), and document.height(). Even ...

Clicking the Less/More button using jQuery

In my current setup, I have a code snippet that loads and displays two comments initially. There is also a button labeled More comments which, when clicked, fetches and shows the remaining comments using AJAX. Upon clicking the More comments button, it tr ...

Showing a JSON file in an HTML page

I've been attempting to showcase a local JSON file on an HTML page. I stumbled upon some information online, but it's causing me quite a bit of confusion. Here is the JSON file I have: { "activities": [ { "name": "C:&bs ...

Top Method for Incorporating Syntax Highlighting into Code Blocks - React Sanity Blog

I'm currently exploring the most effective method to incorporate syntax highlighting into my react sanity.io blog. Here's a look at the article component I've developed using react: import React, {useEffect, useState} from "react"; import ...

How can I utilize angular's $http service to fetch a JavaScript file?

I've been exploring the integration of Angular with Node.js and attempting to establish a connection to a MySQL database. Within my script (server.js), I am utilizing the node mysql module as shown below: var mysql=require('mysql'); var ...

Loop through different JSON objects with unique values using ng-repeat

I am facing an issue with a JSON file that contains three different objects for each area, and I need some help. Here is an example: { "gebieden":"Antwerpen", "onderwerpen":"Gemiddeld netto inkomen per belastingsplichtige", "data_2005":"15084, ...

When utilizing jQuery.Mockjax to simulate the JSON data, the Backbone.Collection.fetch() function consistently results in a 404 error

My setup is pretty straightforward: Main.js: (function($) { "use strict"; var Company = Backbone.Model.extend({ defaults: { title: "", description: "" }, initialize: function() { ...

Is json.Compact capable of validating json data too?

My coworker and I were in the process of developing a minimal logic to handle compacting, validating, parsing, and storing json data received from a client. During our work, we observed that both compacting and validating could be achieved by json.Compact ...

Creating unique div elements with varying sizes that perfectly complement each other

I'm interested in creating a grid of divs that are randomly filled, similar to the image shown. I want them to be completed in a unique way without overlapping with each other. Is there a method to achieve this? ...

Refresh a specific DIV element without having to refresh the entire page

I have a Div Tag that includes Small.php to populate it with information. My goal is to refresh the content every 15 seconds without reloading the entire webpage. I've attempted using JavaScript/jQuery without success. <script type="text/javascrip ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

Leveraging jQuery to interact with MySQL database in PHP Laravel framework

I seem to have hit a roadblock with my database, which is quite intricate. Here's the breakdown of the tables used for the questions: product - contains product details such as shoes productattribute - houses different variations of products like bl ...

Utilizing Ajax to display information

Being a novice in web development, I am working on a database that has a table named customers with columns for customer name and address. On the interface, there is a search field for customers along with another field for customer addresses. My goal is ...

How can you display a border around a <td> element in an HTML table only when it contains data, using jQuery or JavaScript?

My HTML table consists of the following structure: <table class="table table-bordered"> <thead> <tr> <th>Tag</th> <th>Time Code</th> </tr> </thea ...

Using jQuery to apply the "a" class with the addClass method

The html structure below is giving me trouble: <div class="sub"> <a href="#" id="people">People</a> </div> The CSS for the "a" element is as follows: color:#999999; font-size:31px; I am attempting to use jQuery to change ...

What causes <input> elements to vertically center when using the same technique for centering <span> elements? (The line-height of <input> does not match its parent's height)

Important: The height of <div> is set to 50px, and the line-height of <span> is also 50px When 'line-height' is not applied to the <span>, all elements align at the top of the parent. However, when 'line-height: 50px&apo ...

Moving a DIV below a fixed-positioned element

I have a website with a scrollable div. It works well, but I also need an absolutely positioned div on top of it - and it still needs to scroll smoothly without any hindrance. You can check out a basic JSFiddle demonstration here: http://jsfiddle.net/41ra ...