简体   繁体   中英

How to display multiple Countdown timer in php

Firtly, i select all data time from database, but when show to the page only the first one items will show the timer, other items cannot to show the timer.

 <?php
     $stmtAuction = $db->prepare("SELECT * FROM auction WHERE expired_at >= CURDATE() AND status = 'available' ORDER BY expired_at ASC");
                    $stmtAuction->execute();
     if ($stmtAuction->rowCount() > 0) {
                        while ($item = $stmtAuction->fetch()) {
       ?>
          <span id='countdown' value='<?php echo $item['expired_at'];?>'></span>       

<?php
}
?>
    <script>

     $("#countdown").countdown($('#countdown').attr('value'), function(event) {
                $(this).text(
                    event.strftime('%D days %H:%M:%S')
                );
            });
    </script>

how can i show timer for every items??

Your issue is caused by un-unique id s. You have $stmtAuction->rowCount() number of id='countdown' . id s are supposed to be unique. So javascript/jQuery will only find the 1st/unique id='countdown' . You need to use class='countdown' instead -

<?php
    $stmtAuction = $db->prepare("SELECT * FROM auction WHERE expired_at >= CURDATE() AND status = 'available' ORDER BY expired_at ASC");
    $stmtAuction->execute();
    if ($stmtAuction->rowCount() > 0) {
        while ($item = $stmtAuction->fetch()) {
        ?>
            <span class='countdown' value='<?php echo $item['expired_at'];?>'></span>
                  ^^^^^-change from id to class
<?php
        }
    }
    ?>

Now in your javascript, you need to use the class selector - $(".countdown") - and loop over each class using $.each() .

<script>
    $('.countdown').each(function(){
        $(this).countdown($(this).attr('value'), function(event) {
            $(this).text(
                event.strftime('%D days %H:%M:%S')
            );
        });
    });
</script>

a jsFiddle example - https://jsfiddle.net/smh5nhgz/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM