Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Each data only appears 1 data, and when access each data the result is undefined

I have a product div which contains the data-product attribute, its value is object. And I want to put the product data into gtag.

but why when I do each, there is only 1 data? and when I want to access data.id and data.name why is it undefined?

$(document).ready(function(){
  const promotions = []
  
    $(".product-item").each(function(){
    const data = $(this).data('product');
    
    promotions.push({
      "id": data.id,
      "name": data.name
    })
  })
  
  //gtag('event', 'view_promotion', {
    //promotions
  //});
  
  $('.product-item').each(function(){
    $(this).on("click", function(e){
      const data = $(this).data('product')
      console.log(data)
    })
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-item" data-product='{"id" : 123, "name" : "Product 1"}'>
  Product 1
</div>
<div class="product-item" data-product='{"id" : 124, "name" : "Product 2"}'>
  Product 2
</div>
<div class="product-item" data-product='{"id" : 125, "name" : "Product 3"}'>
  Product 3
</div>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Change your HTML code, works for me:

<div class="product-item" data-product='{"id":124,"name":"Product 1"}'>
    Product 1
</div>
<div class="product-item" data-product='{"id":125,"name":"Product 2"}'>
    Product 2
</div>
<div class="product-item" data-product='{"id":126,"name":"Product 3"}'>
    Product 3
</div>
about 4 years ago · Juan Pablo Isaza Report

0

As per the API the attribute value must be a valid JSON including quoted property names.

In your case it is not properly formatted as JSON hence, it is not working. Format your data-product as valid JSON.

Once the JSON is fixed, to loop over promotions

$(document).ready(function(){
  let promotions = []
  $(".product-item").each(function(){
    const data = $(this).data('product');
        
    promotions.push({
      "id": data.id,
      "name": data.name
    })
  })
      
           
  gtag('event', 'view_promotion', {
    promotions
  });
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!