wakirin / Litepicker

Date range picker - lightweight, no dependencies
MIT License
899 stars 132 forks source link

How to create multiple calendar instances and access each one individually? #181

Closed logan-19 closed 3 years ago

logan-19 commented 3 years ago

Hi, How to create multiple calendar instances and access each one individually?

wakirin commented 3 years ago

Hi, What you have tried ?

logan-19 commented 3 years ago

PHP generates (foreach) a list of rooms, JS goes through the list (each) and assigns a calendar to each item, I want to manage each calendar separately to assign dates for each room

PHP

<?php $items = $db->query("SELECT * FROM `items`"); ?>
<?php foreach ($items as $item): ?>
<div class="item">
    <div class="picker" data-picker-id="<?= $item['id']; ?>">
    <div id="in_<?= $item['id']; ?>" class="in">In</div>
    ...
    </div>
</div>
<?php endforeach; ?>

JS

$('.picker').each(function() {
    var id = $(this).attr('data-picker-id');
    var picker = new Litepicker({
        element: document.getElementById('in_' + id),
        ...
        });
});
wakirin commented 3 years ago

You can store pickers in array.

var pickers = [];
$('.picker').each(function() {
    var id = $(this).attr('data-picker-id');
    var picker = new Litepicker({
        element: document.getElementById('in_' + id),
        ...
     });
     pickers[id] = picker;
});
// then you can access to picker by id
// Eg.: pickers[your_id].setDate('2020-02-25');
logan-19 commented 3 years ago

Thank you. Please tell me this call shows an error. How can I make a request correctly?

pickers[id].onShow(function() { console.log('show'); });

var pickers = [];
$('.picker').each(function() {
    var id = $(this).attr('data-picker-id');
    var picker = new Litepicker({
        element: document.getElementById('in_' + id),
        ...
     });
     pickers[id] = picker;

pickers[id].onShow(function() { 
              pickers[id].clearSelection();
              console.log('show'); 
        });
});

I wanted to do some function when showing the picker

wakirin commented 3 years ago

You must use https://litepicker.com/docs/events#show

var pickers = [];
$('.picker').each(function() {
    var id = $(this).attr('data-picker-id');
    var picker = new Litepicker({
        element: document.getElementById('in_' + id),
       setup: (p) => {
          p.on('show', (el) => {
             console.log('show');
          });
       },
        ...
     });
     pickers[id] = picker;
});

OR

pickers[id].on('show', (el) => {
  console.log('show');
});