Search code examples
javascriptjqueryhtmlbootstrap-datetimepicker

jQuery .on('click', function()) not working with bootstrap-datetimepicker


I'm kinda new to using jQuery and I'm using Bootstrap DateTimePicker to display a calendar and I want to retrieve the currently selected date but for some reason the .on('click') function doesn't seem to work when I click on the days.

This is what the html code looks like:

<div style="overflow:hidden;">
    <div class="form-group">
        <div class="row">
            <div class="col-md-8">
                <div id="datetimepicker"></div>
            </div>
        </div>
    </div>
</div>

And what I would like to do would be something like:

$(document).ready(function() {
    $('#datetimepicker').on('click', '.day', function() {
        // Get the selected date.
        var date = $(this).val();
    });
});

The bootstrap html for a single day is like the following:

<td data-action="selectDay" data-day="10/26/2016" class="day active">26</td>
<td data-action="selectDay" data-day="10/27/2016" class="day today">27</td>
<td data-action="selectDay" data-day="10/28/2016" class="day">28</td>

So essentially what I'm looking for is the contents of data-day of the active day.

JSFiddle


Solution

  • I used the following code and it's working for multiple clicks:

    $(document).ready(function() {
        $('#datetimepicker').datetimepicker({
            inline: true,
            format: 'DD/MM/YYYY'
        });
    
        $('div tbody').on('click', 'tr > .day',function(){
            alert($(this).data().day)
        })
    });
    

    jsfiddle

    To access the data stored in data attribute in the html elements, you can search and read more about it on jQuery .data()