Getting the time from a Bootstrap Timepicker

Asher Walther picture Asher Walther · Jul 20, 2012 · Viewed 24k times · Source

I'm trying to get the time from a Bootstrap Timepicker using the getTime function, but only get an error message in the console when I press the button (with ID of my-button, see code below.)

HTML

<div class="input-append bootstrap-timepicker-component">
    <input type="text" class="timepicker input-small">
    <span class="add-on">
        <i class="icon-time"></i>
    </span>
</div>

JavaScript

<script type="text/javascript">
  $('#my-button').on('click', function() {
    alert($('.timepicker').getTime());
  });

  $('.timepicker').timepicker({
    template : 'dropdown',
    showInputs: false,
    showSeconds: false
  });
</script>

Error in the console

Uncaught TypeError: Object [object Object] has no method 'getTime'

I've been trying to figure this out for hours. I thought I could use the source code to learn how to use the picker, and it looks like there's a getTime() function, but I can't for the life of me figure out how to use it. I'm using Rails, for what it's worth. Thanks guys!

Answer

projectgus picture projectgus · Sep 18, 2012

FWIW it is possible to call getTime() but it can't be called directly because $('.timepicker') returns the <input> element from the DOM, not the actual timepicker object.

It's not mentioned in the documentation, but if you look at the bootstrap-timepicker.js source then the binding function ($.fn.timepicker) stores a reference to the actual timepicker object against the DOM element, using jQuery's data() feature.

So, this works:

$('.timepicker').data("timepicker").getTime();

(Of course getTime() still just returns a string, so in this case the parent's suggestion of using val() is probably cleaner unless you think there might be invalid data typed into the field, and not yet cleaned by the timepicker.)