Search code examples
phpjquerycountdown

problem jquery countdown only show timer for product1, but not show product2, .. n product


    <script type="text/javascript">
       $(function () {
           var id = $("#id").val();
           var endDate = $("#endtime_" + id).val();
           $('#defaultCountdown_'+id).countdown({until: endDate});
        });
    </script>

    while($row = mysql_fetch_assoc($result))
    {
...
    ?>
    <input type="hidden" id="id" value="<?php echo $row['id'] ?>" />
    <span id="<?php echo "defaultCountdown_" . $row['id'] ?>"></span>
    <input type="hidden" id="<?php echo "endtime_" . $row['id']?>" value="<?php echo $row['end_time'] ?>" />
    <?php
    }

Help me !!!


Solution

  • The problem is, you are creating your hidden inputs with the same value for the html attribute ID:

    <input type="hidden" id="id" value="<?php echo $row['id'] ?>" />
    

    This won't work, because ID's have to be unique.

    Modify your PHP code, to have a unique ID and additional a class name for all hidden inputs, to be able to select them all with jQuery.

    while($row = mysql_fetch_assoc($result))
    {
    ?>
    <input type="hidden" class="hiddenId" id="id_<?php echo $row['id'] ?>" value="<?php echo $row['id'] ?>" />
    <span id="<?php echo "defaultCountdown_" . $row['id'] ?>"></span>
    <input type="hidden" id="<?php echo "endtime_" . $row['id']?>" value="<?php echo $row['end_time'] ?>" />
    <?php
    }
    

    Then iterate thru all hidden inputs by selecting with $(".hiddenId"), get the ID, and start the countdown.

    <script type="text/javascript">
    $(function () {
        $(".hiddenId").each(function() {
            var id = $(this).val();
            var endDate = $("#endtime_" + id).val();
            $('#defaultCountdown_'+id).countdown({until: endDate});
        });
    });
    </script>