The list countdown for loop only appears in the initial iteration

Hey there, I'm currently facing an issue with duplicating my JavaScript countdowns and displaying images of cards on each loop iteration. Strangely, the countdown only appears in the first instance even though it's within the loop. I'm seeking advice on what might be causing this discrepancy.

In addition to this problem, there are other functionalities like adding cards to a webpage upon clicking, triggering individual timers for each card. However, the primary concern remains unresolved – the duplication glitch within the loop. Interestingly, when I replace the countdown code with plain text in the table, it shows up correctly on every card.

Your assistance is greatly appreciated.

Here's a snippet of the HTML:

  <div class="container">
      <br>
      <div class="row">
        <h2 class="bold_font text-align-center">LIST OF CLAIMED CARDS</h2><br>
        <?php
          $i = 0;
          foreach($lstOrders as $rowOrder) {
        ?>
          <div class="col-md-4 spacer">
            <div class="col-md-12">
              <?php
                $productid = $rowOrder['productid'];
                $rowProduct = $mcProduct->SelectObj_ProductId($db, $productid);
              ?>
            </div>
            <div class="col-md-12">
              <?php
                for($j = 0; $j < $rowProduct['packageid']; $j++) {
                  echo(' <span class="glyphicon glyphicon-gift color-black"></span> ');
                }
              ?>
            </div>


            <div class="col-md-12">
              <a href="info-detailed.php?i=<?php echo($rowProduct['productid']) ?>">
                <img src="../img/uploads/<?php echo($rowProduct['photosrc']) ?>" class="img-responsive clinic">
                <img src="../img/shadow-bottom.png" class=" img-responsive">
              </a>

            </div>

            <table align="center">
              <tr>
                <td colspan="4">Reclaim This Coupon In:<hr></td>
              </tr>
              <tr align="center">
                <td id="c_countdown"></td>
              </tr>

            </table>
          </div>
        <?php
            $i = $i + 1;
            if($i >= 3) {
              echo('<div class="col-md-12"></div>');
              $i = 0;
            }
          } ?>

        <!-- Empty Col -->
        <div class="col-md-3 form-group">
        </div>
      </div> <!--row-->

      <div class="row">
        <div class="col-md-12 spacer">
        </div>
      </div>

    </div>

JAVASCRIPT: (c_countdown)

var countDownDate = new Date("Jan 5, 2019 15:37:25").getTime();

var x = setInterval(function() {

  var now = new Date().getTime();

  var distance = countDownDate - now;

  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  document.getElementById("c_countdown").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

  if (distance < 0) {
    clearInterval(x);
    document.getElementById("c_countdown").innerHTML = "EXPIRED";
  }
}, 1000);

https://i.stack.imgur.com/afG59.png

added TEST in table

https://i.stack.imgur.com/QzXiC.png

Answer №1

Avoid using 'c_countdown' as an id because ids should be unique on a webpage. When using document.getElementById, it will only target the first element with that id. It is recommended to use classes instead and then iterate over elements.

To achieve this in JavaScript, you can implement the following code after converting the id attribute to a class in the HTML:

document.querySelectorAll('.c_countdown').forEach(function(elem){
  elem.innerHTML = 'whatever you want to set here'
})

Answer №2

Make sure to include a semicolon after each echo statement in the code below:

<a href="info-detailed.php?i=<?php echo($rowProduct['productid']); ?>">
    <img src="../img/uploads/<?php echo($rowProduct['photosrc']); ?>" class="img-responsive clinic">
    <img src="../img/shadow-bottom.png" class="img-responsive">
  </a>

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

Issue in Angular form: Element removal from the DOM does not remove it at the specified index, instead removes the last item

I'm encountering an issue where the wrong element is being removed from the DOM. In my onDelete() method, I am deleting a specific FormControl at a certain index, but in the actual DOM, it's removing the last item instead of the intended one. Fo ...

Is there a way to enlarge the font size for a complete tag?

I'm having trouble with a project. One of the tasks is to use jQuery or JavaScript to increase the font size of a paragraph. The console statements are incrementing by +1 with every mouse click (the first click adds 1, the second adds 2, and so on). ...

Adding a "Learn More" hyperlink in a JavaScript loop

To implement a read more link in JavaScript, I utilize the following function: <script type="text/javascript"> function toggleContent(v) { var vbox = document.getElementById('vbox'); vbox.style ...

Verify the presence and delete a table row from the JSON data that is returned

Is there a way to verify the presence of a label in the JSON response and exclude it from the displayed row in my table? In the code snippet below, you can observe that I am returning 'Page Name not defined'. I want to hide this label and any re ...

Ways to quickly terminate a pipeline in a JavaScript transformation

Issue: I am facing a challenge with handling large files (>10GB). At times, I need to process the entire file while other times I only need to sample a few lines. The processing mechanism involves a pipeline: pipeline( inStream, ...

Trouble with parsing dates in JavaScript using Moment.js

I'm retrieving dates from SQL Server that are passing through ASP.NET, and then iterating through a list of objects in jQuery to display the dates along with other data. However, regardless of the various date/time values coming from the database, the ...

A simple guide on how to display a child object in a materialUI select dropdown from a parent object

I am developing a ReactJS application where I aim to showcase child objects from the parent object in a dropdown using materialUI select. Despite attempting to iterate over the object using the map() function, I haven't been able to retrieve values up ...

Executing asynchronous JavaScript code within a Golang request: a comprehensive guide

I am in need of a solution to retrieve the content from dynamically generated pages using ajax on a website, specifically with code written in golang. I have found examples for non-ajax pages but struggling to find one that works for ajax pages. Any guid ...

Exploring the possibilities of developing WebComponents within Angular using TypeScript

My Angular application was originally created using the default method with ng new project-name". However, for performance reasons, I had to incorporate single standard WebComponents. The JavaScript code associated with these components is stored in a ...

Error in jQuery and Canvas Image Crop: The index or size is invalid, exceeding the permissible limit

Recently, I downloaded and installed the Canvas Image Crop plugin from CodeCanyon but encountered a problem specifically on firefox. An error message kept popping up whenever I tried to upload certain images: "Index or size is negative or greater than the ...

What causes the disappearance of CSS styles when attempting to modify the className in react js?

I am currently working on a basic react application, and I am trying to dynamically change the name of a div element using the following code snippet - <div className={'changeTab ' + (page.login ? 'leftSide' : 'rightSide')} ...

The onCall function in Firebase's realtime database does not provide a response data object when executing the remove() operation

When using onCall to perform a remove operation from a realtime database, I encountered an issue where the response only returned null instead of the expected data object. Strangely, I have used onCall for other operations like update and always received a ...

Is there something incorrect with the incrementation in JavaScript?

for (let i = 0; i < 5; ++i){ alert(i); } for (let i = 0; i < 5; i++){ alert(i); } Both of these constructs get the same result: 0, 1, 2, 3, 4. But what are the underlying differences between them? And does the choice of increment in a for l ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

In order to avoid conflicts, please update the version code of your APK as there is currently one with version code 1. How can I go about changing the version?

My attempt to upload an apk file on Google Play has hit a roadblock. The apk file was created using Unity3D. Google Play is giving me an error message stating that I need to use a different version code for my APK because a version with code 1 already exis ...

Tips for updating the content of a DIV element on a separate page

One question that often arises is how to change the content of a div element on a different page within a website. While it is common to use Ajax to dynamically update div content within the same page by fetching data from an external .html file, the proce ...

Utilizing the length property of arrays for mathematical computations

I'm currently exploring the possibility of achieving this using javascript. In my scenario, I have an array named cart that consists of objects with product.quantity, and I aim to incorporate the value of cart.length in a calculation. However, I cons ...

Transformer Class: An object containing properties that are instances of another class

class ClassA { x: number; y: number; sum(): number { return this.x + this.y; } } class ClassB { @Type(() => ClassA) z: {[key: string]: ClassA}; } const b = transformObject(ClassB, obj); const z = b.z[key]; const s = z.s ...

Troubleshooting issues with adding child elements in JavaScript

Styling with CSS: ul #allposts li{ height: 50px; width: 50px; background-color: yellow; border: 1px solid yellow; } Creating HTML structure: <ul id = "allposts"></ul> Adding JavaScript functionality: var container = documen ...

"Learn how to handle exceptions in Nest JS when checking for existing users in MongoDB and creating a new user if the user does

Below is the implementation of the addUser method in users.service.ts - // Function to add a single user async addUser(createUserDTO: CreateUserDTO): Promise<User> { const newUser = await this.userModel(createUserDTO); return newUser.save() ...