1

I have a PHP For that loads 5 times the same set of input fields for multiple entries.

At the same time, I have a "datepicker" javascript to be run in the date field.

The issue is that only in the first row the datepicker is working. For the next 4 rows loaded, the datepicker doesn't run in the date field.

Code:

    <?php 
    for ($i=0;$i<5;$i++)
    {
    ?>
    <tr>
        <td><input id="includeItem" type="checkbox" onchange="includeMore" name="item<?=$i?>"></td>
        <td><input name="id<?=$i?> style="color:#888;" disabled="disabled"></td>
        <td><input class="formItems" id="datepicker" name="date<?=$i?>"></td>
        <td><input class="formItems" name="description<?=$i?>"></td>
        <td><input class="formItems" name="amount<?=$i?>"></td>
    </tr>
    <?php } ?>

Javascript:

<script>
  $(document).ready(function() {
    $("#datepicker").datepicker({
    dateFormat: 'yy-mm-dd'
    });
  });
</script>

3 Answers 3

3

IDs should be unique on a page. That means that when you try to select an ID with jQuery it will stop on the first one it finds.

You should use a class to circumvent this, like so.

Code:

    <?php 
    for ($i=0;$i<5;$i++)
    {
    ?>
    <tr>
        <td><input id="includeItem" type="checkbox" onchange="includeMore" name="item<?=$i?>"></td>
        <td><input name="id<?=$i?> style="color:#888;" disabled="disabled"></td>
        <td><input class="formItems" class="datepicker" name="date<?=$i?>"></td>
        <td><input class="formItems" name="description<?=$i?>"></td>
        <td><input class="formItems" name="amount<?=$i?>"></td>
    </tr>
    <?php } ?>

Javascript:

<script>
  $(document).ready(function() {
    $(".datepicker").datepicker({
    dateFormat: 'yy-mm-dd'
    });
  });
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

The same id is not allowed it must be unique - id="datepicker"

Comments

1

Use a class as opposed to an ID.

Give each input a class of "datepicker" and change your jQuery selector to $(".datepicker")

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.