Combine the rows using the $.each function in the response

I am struggling with an issue related to displaying products fetched from an ajax response. The problem arises when multiple products share the same image, causing redundancy in the table. I aim to identify all products with identical rec.Photo and showcase them on a single row, accompanied by a message stating "we have variants of similar products - click on the photo to see more..." My main concerns are: a) How can I accurately identify all products with the same photo? b) Is there a way to display the message "see more similar products..." on one row without disrupting the loop?

  $.each(response, function (i, rec) {
                                 if (i > 0) {

                                     strproductlist += '<div class="gridItem listView">';
                                     strproductlist += ' <div class="gridItemContent">';
                                     strproductlist += '<div class="productPhoto">';
                                     strproductlist += '<a title="' + rec.ProductName + '"  href="ProductDetails.aspx?productid=' +
 rec.ProductID + '">';
                                     strproductlist += '<img alt="' + rec.ProductName + '" src="' + rec.Photo + '">';
                                     strproductlist += '</a>';
                                     strproductlist += '</div>';
                                     strproductlist += '<div class="listViewProductDet">';
                                     strproductlist += '<h2>';
                                     strproductlist += '<a title="" href="ProductDetails.aspx?productid=' + rec.ProductID + '">' +
 rec.ProductName + '</a>';
                                     strproductlist += '</h2>';
                                     strproductlist += '<p class="productCode">' + rec.ProductCode + '</p>';
                                     strproductlist += '<ul class="fieldlist">';

    strproductlist += '</div>';
                                     strproductlist += '</div>';
                                     strproductlist += '</div>';
                                 }

//Edit I am providing details for four sample records where three of them share the same image.

-------- ProductID=1 ProductName=product1 Photo=~/products/product1.jpg ProductCode=001 -------- ProductID=2 ProductName=product2 Photo=~/products/product1.jpg ProductCode=002 -------- ProductID=3 ProductName=product3 Photo=~/products/product1.jpg ProductCode=003 -------- ProductID=4 ProductName=product4 Photo=~/products/product2.jpg ProductCode=004

Answer №1

I believe I have found the solution you were seeking. My approach involves dynamically adding elements to the body at each step in order to check if a specific image with the same url already exists in the body. If it does, then I refrain from rendering it and proceed to display what you require, such as view more similar products. Currently, I am displaying an alert indicating that the image is present. You can implement the logic for displaying view similar products in that section!

CHECK OUT THE FIDDLE DEMO HERE

var data=[
    {"ProductID":"1","ProductName":"product1", "Photo":"https://www.runtastic.com/shop/media/catalog/product/cache/2/image/9df78eab33525d08d6e5fb8d27136e95/o/r/orbit_with_clip_en_1.png","ProductCode":"001"},
    {"ProductID":"2","ProductName":"product2", "Photo":"https://truegamers.com.my/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/3/_/3_83_6.jpg","ProductCode":"002"},
    {"ProductID":"3","ProductName":"product3", "Photo":"https://www.runtastic.com/shop/media/catalog/product/cache/2/image/9df78eab33525d08d6e5fb8d27136e95/o/r/orbit_with_clip_en_1.png","ProductCode":"003"},
    {"ProductID":"4","ProductName":"product4", "Photo":"https://truegamers.com.my/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/3/_/3_83_6.jpg","ProductCode":"004"}
];

$.each(data, function (i, rec) {
    var strproductlist="";
    
    var imgname=rec.Photo;
    if($('.gridItem img[src="'+imgname+'"]').length)
    {
       alert('image present');
    }
    else
    {
        strproductlist += '<div class="gridItem listView">';
        strproductlist += '<div class="gridItemContent">';
        strproductlist += '<div class="productPhoto">';
        strproductlist += '<a title="' + rec.ProductName + '"  href="ProductDetails.aspx?productid=' +
 rec.ProductID + '">';
        strproductlist += '<img alt="' + rec.ProductName + '" src="' + rec.Photo + '">';
        strproductlist += '</a>';
        strproductlist += '</div>';
        strproductlist += '<div class="listViewProductDet">';
        strproductlist += '<h2>';
        strproductlist += '<a title="" href="ProductDetails.aspx?productid=' + rec.ProductID + '">' +
 rec.ProductName + '</a>';
         strproductlist += '</h2>';
         strproductlist += '<p class="productCode">' + rec.ProductCode + '</p>';
         strproductlist += '<ul class="fieldlist">';
         strproductlist += '</div>';
         strproductlist += '</div>';
         strproductlist += '</div>';
         $('body').append(strproductlist)
    
    }
    
});
img{
    width:100px;
    height:100px;
}
.gridItem{
    float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


UPDATE

VIEW UPDATED DEMO HERE

In place of the alert within your if statement, I have replaced it with console.log, which now displays the parent element containing that image.

if($('.gridItem img[src="'+imgname+'"]').length)
{
       console.log($('.gridItem img[src="'+imgname+'"]').closest('.gridItem'));
}

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

Issues encountered transferring data using wp_localize_script

I need help passing PHP data to a JavaScript script in my project. To achieve this, I am utilizing the wp_localize_script function. wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js'); wp_register_script(&apos ...

Tips for updating the pagination layout in Material UI Table

Currently, I am attempting to modify the background color of the list that displays the number of rows in MUI TablePagination. <TablePagination style={{ color: "#b5b8c4", fontSize: "14px" }} classes={{selectIcon: ...

I've come across certain challenges when setting values for Vue data objects

I'm having trouble with a Vue assignment. Here is my code: new Vue({ el: "#alarmEchartBar", data: { regusterUrl: Ohttp + "historicalAlarmRecord/chart", regDistrictUrl: Ohttp + "district", regStreetUrl: Ohttp + "street/", regCameraUrl: ...

Avoid triggering a keydown event if certain div elements have been clicked

When the user presses the space bar, my script is set up to perform certain actions, such as stopping an audio player: $('html').keydown(function(e){ if(e.keyCode == 32){ // Stop the audio player } } However, an issue arises when a ...

Disabling Multiple Days in a ReactJS Calendar Component

Hey there, I hope everyone is doing well! I've been tackling a ReactJS calendar challenge and have hit a roadblock that has me stumped. I'm pulling in days from a local API and using an if statement to determine whether the current day of the mo ...

The error in Node.js restify — when a callback serving a request is mistakenly treated as a static

Setting up a node js web server with the restify module is my current task. server = restify.createServer(); server.post('/getData', DataManager.getData); The handler for the /getData path is defined as follows: DataManager.prototype.getData = ...

AngularJS: Oops! We have encountered an unidentified provider error

There is a simple issue that works in the jsfiddle but not in my file. I am attempting to add data to the "factory" of the module and then utilize it within my controllers. Here is the relevant code snippet: var challengesApp = angular.module('chall ...

Ways to incorporate external JavaScript files into a React component

I have been attempting to incorporate external javascript files into my react component. When I included them in a basic html file using script tags, everything worked smoothly. However, I am unsure of how to achieve this within a react component. < ...

How can I use AJAX to read an image file and display it on a Canvas?

Is there a way to read an image from my server using Ajax and then display it on Canvas? I am aware that this can be achieved by using normal image tags and canvas draw methods, as shown below: <img id="myImage" src="./ColorTable.PNG" style="display:n ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

I'm looking to have the checkbox automatically checked when the <p> Tag is clicked in JavaScript

I need to modify the checkbox input so that when I click on any Todo Item, the checkbox is checked. However, after implementing the code below, it only works for the first element clicked. How can I make it work for each individual todo list item without c ...

Is there a way in jquery or any other method that specifically detects changes only in direct child nodes?

I came across a jQuery method called DOMSubtreeModified that can detect the insertion of child nodes within a specific DOM. However, I noticed that this method detects the insertion of all child nodes, not just the immediate ones. Is there a jQuery met ...

Prevent further triggering of the .click function when the user clicks repeatedly

Is there a way to prevent the .click function from executing if the user clicks too many times? This is my current code: $('button').click(function() { $('#bg').fadeToggle('200'); }); Check out the jsfiddle DEMO ...

Retrieving the values from an HTTP post request

Currently, I'm facing an issue with receiving a large amount of http post data from an external website to my page. I am finding it challenging to separate and manage this data effectively. Here's an example of what I'm dealing with: Someon ...

displaying JSON data in two separate Highcharts bar charts

Looking to display data using a bar highcharts, with only two bars, each with data... Here's the breakdown: I have a bar chart with 2 categories, each containing subcategories. Here are the data for the categories: First category: subCategory 1-1 ...

Creating a variable in JavaScript using Smarty in Prestashop 1.6

I am currently facing an issue with defining a JavaScript variable that fetches its value from a Smarty variable. In my PHP controller, here is what I have implemented: public function hookDisplayBackOfficeHeader() { $this->context->controller-&g ...

The Follow/Unfollow button fails to function properly when attempting to unfollow by using the same ajax call

A scenario where dynamically generated buttons (anchors) are displayed on a page, each with a unique ID and a common class. With the class, I am able to retrieve the ID using jQuery and send it to the controller for processing. Although I can successfully ...

A guide on extracting and transforming a nested Object into a new object containing essential information

Here is a nested Object that I have. It needs to be read and converted. { "_id": "config", "_rev": "11-57a", "config": { "A": { "a1": { "required": true, "editable": true }, "a2": { "required": true, ...

How can I add an image to a canvas using a button?

Having trouble with my studies and looking to create a custom shirt website. Posted below is the beginner code I have: If anyone knows how to upload an image onto a shirt canvas using a button, as well as change the shirt color with another button, please ...

My attempt at deploying my personal React App project on Vercel was unsuccessful

// encountering error during deployment on Vercel npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @testing-library/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99b8c888a9da9d8da ...