How to generate gtag item list foreach product using JQuery

164 Views Asked by At

Here is a short product list for the reference. I would like to have my gtag generated below the product list. How can I do this?

<div class="product">
    <div class="name">Audi</div>
    <div class="price">21.000</div>
</div>  
<div class="product">
    <div class="name">Opel</div>
    <div class="price">17.000</div>
</div>
<div class="product">
    <div class="name">Cadillac</div>
    <div class="price">33.500</div>
</div>

Here I need all the product values in the items parts.

<script>
gtag("event", "view_item_list", {
  item_list_id: "category_products",
  item_list_name: "Products from a category",
  items: [
    {
      item_name: "Audi",
      price: 21.000,
      index: 0
    },
    {
      item_name: "Opel",
      price: 17.000,
      index: 1
    },
    {
      item_name: "Cadillac",
      price: 33.500,
      index: 2
    }
  ]
});
</script>

Updated code using the method from the answer below. So now, if I pass the products variable, it throws a syntax error at the line gtag("event", "view_item_list". The error by itself says Uncaught SyntaxError: missing ) after argument list

<script>

var products = [];
    
$(".product").each(function(i) {
  products.push({
    "name": $(this).find(".name").text(),
    "price": $(this).find(".price").text(),
    "index": i
  })
});

gtag("event", "view_item_list" {
  item_list_id: "category_products",
  item_list_name: "Products from a category",
  items: products
});

</script>
1

There are 1 best solutions below

8
Swati On

You can use .each loop and inside that get the value of name & price using .find() and .text() method . Then , pass the generated array to your gtag items parts .

Demo Code :

var items = [];

$(".product").each(function(i) {
  items.push({
    "name": $(this).find(".name").text(),
    "price": $(this).find(".price").text(),
    "index": i
  })
})

console.log(items)
//pass items in your gtag
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product">
  <div class="name">Audi</div>
  <div class="price">21.000</div>
</div>
<div class="product">
  <div class="name">Opel</div>
  <div class="price">17.000</div>
</div>
<div class="product">
  <div class="name">Cadillac</div>
  <div class="price">33.500</div>
</div>