1

I have this problem where I have to set multple jQuery timepicker's default value (they are put in an HTML table) from the PHP array which is looped.

Here's the JS code for one timepicker textbox:

$(document).ready(function(){

    $('.timepicker').timepicker({
        timeFormat: 'HH:mm',
        interval: 1,
        minTime: '7',
        maxTime: '7:00pm',
        defaultTime: '<?php echo $records[$i]->time_in ?>',
        dynamic: false,
        dropdown: true,
        scrollbar: true
    });
});

</script>

and the table is populated thru a loop:

<table border=1>
   <tr>
     <th>Time In</th>
   <tr>
   @for($i=0;$i<count($records);$i++)
   <tr>
     <td><input type="text" class="timepicker" id=start_shift_$i /></td>
   </tr>
   @endfor
</table>

What I'm trying to do is to populate the timepickers default value with the time_in values looped from an array.

Hope you can help. Thanks!

Rav
  • 1,327
  • 3
  • 18
  • 32

1 Answers1

1

You can take an extra attribute to the input field as 'default_date' and set the default date value to this attribute.

 <table border=1>
   <tr>
     <th>Time In</th>
   <tr>
   @for($i=0;$i<count($records);$i++)
   <tr>
     <td><input default-date="<?php echo $records[$i]->time_in ?>" type="text" class="timepicker" id=start_shift_$i /></td>
   </tr>
   @endfor
</table>

Now you can access default date attribute like this ...

$('.timepicker').each(function(i, obj) {
     $(this).timepicker({
        timeFormat: 'HH:mm',
        interval: 1,
        minTime: '7',
        maxTime: '7:00pm',
        defaultTime: $(this).attr('default-date'),
        dynamic: false,
        dropdown: true,
        scrollbar: true
    });
});
Rakesh
  • 505
  • 5
  • 12
  • 1
    You can add arbitrary custom attributes to any html element, but they should start with `data-`. This is the "official" statement for html5. If you use other names it will most likely still work but your html is considered "invalid". See here: https://stackoverflow.com/a/1735268 – Carsten Massmann May 24 '19 at 05:41
  • 1
    @car10m yes you are right, 'dsta-attr-name' is correct format. – Rakesh May 24 '19 at 05:57