Search code examples
jquerytimepicker

Change event firing when initiating the time picker on inputs


In my code, I append an input to a div that's rendered in the page like so:

$("#output-area").append("<input type='text' class='timepicker' /><input type='text class='timepicker' />

After the append, I initiate the timepicker like so:

$('.timepicker').timepicker({
     timeFormat: 'h:mm p',
     interval: 30,
     minTime: '12:00am',
     maxTime: '11:30pm',
     defaultTime: '9:00am',
     dynamic: false,
     dropdown: true,
     scrollbar: true,
     change: function(){
           console.log("triggered");
     }
});

Oddly enough, when I the time picker is created, the change event is triggered the moment they are added to the DOM. I thought the change event triggers only when the values of the input have changed vs created.


Solution

  • Without modifying the plugin itself you could initialize in a loop and set a flag for something like isInit within each instance so you don't react to the initial call:

    $('.timepicker').each(function() {
      var isInit = true;
      $(this).timepicker({
        timeFormat: 'h:mm p',
         .....
        change: function() {
          if (!isInit) {
            console.log("triggered");
          }
          isInit = false
        }
      });
    });
    

    Perhaps there is another event you can use but there are numerous timepicker plugins around so not sure which you are using.

    To me this seems like a bug in the plugin