Time picker inside a loop for

风格不统一 提交于 2019-12-12 01:17:26

问题


I have form with a loop and I would like to use a time picker. The problem is outside the loop it works fine but inside the loop it doesn't work. For the 3 input box it's possible to see the time picker but when select the time it will change only the first box.

<?php for ($i = 1; $i <= 3; $i++) { ?>
    Time <input type='text' name='timepicker[<?= $i ?>]' class="datepicker_dynamic" id='timepicker[<?= $i ?>]' value=''/>
<?php } ?>

<script type='text/javascript'>
    $(document).ready(function() { 
        $('.datepicker_dynamic').timepicker({
            showLeadingZero: false,
        });
    });
</script>

回答1:


I did some rearranging to your code:

<?php for ($i = 1; $i <= $_SESSION["number"]; $i++) { ?>
    Time
    <input type='text' name='timepicker[<?= $i ?>]' id='timepicker_<?= $i ?>' value=''/>
    <script type='text/javascript'>
        $(document).ready(function() { 
            $('#timepicker_<?= $i ?>').timepicker({
                showLeadingZero: false,
            });
        });
    </script>
<?php } ?>

Again, I agree with @Brad that it's probably a good idea not to be generating this much JS unnecessarily, especially when you could do the following with the same results if all the datepickers are identical in functionality:

<?php for ($i = 1; $i <= $_SESSION["number"]; $i++) { ?>
    Time
    <input type='text' name='timepicker[<?= $i ?>]' class="datepicker_dynamic" id='timepicker[<?= $i ?>]' value=''/>
<?php } ?>

And use the following JS:

<script type='text/javascript'>
    $(document).ready(function() { 
        $('.datepicker_dynamic').timepicker({
            showLeadingZero: false,
        });
    });
</script>

Edit: In the end, the problem ended up being an improper usage of the PHP open tag <?. Adding a small explanation here for future reference:

  • <?php ?>: The default php open and close tags, always enabled by default
  • <? ?>: The php short open tag. This may be disabled by default, so check your PHP settings and enable this before using it.
  • <?= ?>: shorthand for <?php echo ?>. Again, might be disabled by default, so check your PHP settings and enable before using.

To enable the short open tags, check your PHP.ini file for short_open_tag



来源:https://stackoverflow.com/questions/17800524/time-picker-inside-a-loop-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!