1

I have a PHP loop like this <?php foreach ($products as $product) { ?> now inside this loop I will be creating some div. the number of divs created depends on number of products. Also, I have a javascript function that creates a countdown.

Now I am trying to create a unique countdown in every div that gets created. .ie unique countdown for every product. here is the code that generates the coundown

$(function(){$('.counter').countdown({startTime:"<?php echo $product['time']; ?>" });}); 

and this is what I have inside the php loop that creates the divs

<div class= 'counter' ></div>

now what this gives me is the same counter in all the divs. I'm new to all this, I haven't slept in hours trying to learn and figure out what I'm doing wrong.

EDIT:

So I still have not get what I want. $('.counter').each(function() { $(this).countdown(....
produce the same counter for all the divs. and for some reason I get syntax error when I try to use $('#product-').countdown(... in order to create a unique selector.

2 Answers 2

1

This won't work as the selector .counter will find all elements with the class name counter.

Assuming that time varies for every product and that you have a unique identifier for every product, you could solve this by assigning an unique ID to every div-element, and use this as a means to trigger the countdown process:

<div id="product-<?php echo $product['id']; ?>" class="counter"></div>

And the Javascript-code:

$('#product-<?php echo $product['id']; ?>').countdown({startTime: '...'});

I'd suggest a design pattern though where you don't have to generate javascript code like this.

Sign up to request clarification or add additional context in comments.

4 Comments

what do you mean to design a pattern ? you were right by the way.
I am trying to follow your suggestion. but $('#product-<?php echo $product['product_id']; ?>') gives me an error.
I know too little of your source code to be able to determine what is wrong. A syntax error means that there is a syntactical error somewhere in your Javascript code. Make sure to examine the generated jQuery thoroughly.
Thank you Zanathel. For some reason when ever I tried to use the product id inside the selector , I get a syntax error. What I ended up doing was I created a count++ inside my for loop and used that instead of the product id to create the unique selectors. But Thank you, your method was What I was looking for.
0

What you need is each()

$('.counter').each(function() { $(this).countdown({startTime:"" }); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.