Search code examples
javascriptjquerytimepicker

2 jQuery Timepickers -- How to Distinguish (jquery.timepicker)


I'm using jQuery.timepicker (not sure how widely this plugin is used -- it was created by Jon Thornton, Git: https://github.com/jonthornton/jquery-timepicker and Sample Page: http://jonthornton.github.io/jquery-timepicker/)

I have 2 timepickers that I've created, StartTime and EndTime, which populate dropdowns with 5-min.-interval choices from 00:00 to 23:59.

e.g.,

$('#startTime').timepicker({
      'minTime': '12:00am',
      'maxTime': '11:59pm',
      'step': '5', 
      'showDuration': 'false'
});     

$('#endTime').timepicker({
      'minTime': '12:00am',
      'maxTime': '11:59pm',
      'step': '5', 
      'showDuration': 'false'
}); 

But in the final HTML this inserts identical supporting DIVs that pop up when clicking on an input field. As far as I can tell they're not distinguished by position, ID, or class.

<div class="ui-timepicker-wrapper" tabindex="-1" style="position: absolute; top: 230.233px; left: 345.667px; display: none;">
    <ul class="ui-timepicker-list">
       <li>12:00am</li>
       <li>12:05am</li>
       ...
</ul></div>

for both. Is there any way I could distinguish them? I need to delete some entries from #2 upon selection in #1. The following doesn't work because it deletes from the wrong list. In this example, I need to delete from #2's list the time selected in #1.

$('#endTime').on('showTimepicker', function() {
    var current = $('.ui-timepicker-list li').filter(function() { // Exact match necessary
        return $(this)[0].childNodes[0].textContent == $('#startTime').val();
    });
    if (current.length) {
        $(current).remove();
    }
});

Solution

  • When creating the timepicker, you can use the className: option to specify a class to give the HTML element containing the dropdown. So give the two timepickers different classes:

    $('#startTime').timepicker({
          className: 'startTime',
          'minTime': '12:00am',
          'maxTime': '11:59pm',
          'step': '5', 
          'showDuration': 'false'
    });     
    
    $('#endTime').timepicker({
          className: 'endTime',
          'minTime': '12:00am',
          'maxTime': '11:59pm',
          'step': '5', 
          'showDuration': 'false'
    });
    
    $('#endTime').on('showTimepicker', function() {
        var current = $('.endTime li').filter(function() { // Exact match necessary
            return $(this).text() == $('#startTime').val();
        });
        current.remove();
    });
    

    You also don't need that verbose code to get the text of the list item, just use $(this).text(). And there's no need to check the length of current; if it's empty, remove() won't do anything (almost all jQuery methods have no problem processing empty collections).