Search code examples
javascriptjquerytimepicker

JQUERY : How to loop Array disableTimeRanges from json


how to display all indexes from array to disableTimeRanges array? this my code

<input id="tanggal" type="date">
<input id="horaInicio" type="text" class="time" />

<script type="text/javascript">
        $(document).ready(function() {
        $('#tanggal').on('change', function() {
            var tanggal = $(this).val();
                if(tanggal) {
                $.ajax({
                    url: '{{url("/tanggal")}}/'+encodeURI(tanggal),
                    type: "GET",
                    dataType: "json",
                    success:function(data) {
                    $.each(data, function(key, value) {
                        $('#horaInicio').timepicker('remove').timepicker({'disableTimeRanges': [ [value['dari'], value['sampai']], ] });
                        });
                    }
                });
                }
               });
            });
    </script>

index [0] : 3:00am, 4:00am

index [1] : 6:00am, 9:00am

but my code just displays the last index, I want to display all of my indexes. thanks:)


Solution

  • It is because you are overwriting the disableTimeRanges property for "each" array element. So only the last one is recorded.

    To fix this refer to the sample from the documentation:

    $('#disableTimeRangesExample').timepicker({
        'disableTimeRanges': [
            ['1am', '2am'],
            ['3am', '4:01am']
        ]
    });
    

    So first, transform the data from the server to match this format and place it into a new array. Then simply pass the array into the 'disableTimeRanges' property.

    Change:

    $.each(data, function(key, value) {
        $('#horaInicio').timepicker('remove').timepicker(
          {'disableTimeRanges': [[value['dari'], value['sampai']], ] });
    });
    

    To:

    let exclusions = data.map(item=>[item.value['Dari'], item.value['sampan']]);
    $('#horaInicio').timepicker('remove').timepicker(
              {'disableTimeRanges': exclusions });