Skip to main content

๐Ÿ“† Adding a Date Picker to a Report with JavaScript

This article is a work in progress.

Suppose you had a report with a parameter like weekof that drives date comparison filters. This would be really cool, except users would have to manually put that URL parameter in each time they wanted to change the report's dates.

With a little JavaScript, you can provide the user with a convenient datepicker. Because JQuery and JQuery UI are already used in Slate pages, much of the work is done for us. Here's what I put into the source code of a static content block:

<script>
    //Wait for DOM to load before doing anything
    $(function () {

        function getUrlParameter(sParam) {
            var sPageURL = window.location.search.substring(1);
            var sURLVariables = sPageURL.split('&');
            for (var i = 0; i < sURLVariables.length; i++) {
                var sParameterName = sURLVariables[i].split('=');
                if (sParameterName[0] == sParam) {
                    return sParameterName[1];
                }
            }
        };

        //Attach a datepicker to the text box with ISO 8601 date format.
        $(function () {
            $("#datepicker").datepicker({
                dateFormat: "yy-mm-dd"
            });
        });

        //If the datepicker text box changes, reload the page with the new date
        $('#datepicker').change(function (appendUrlParam) {
            var currUrl = "https://" + location.host + "/manage/report/render?id=" + getUrlParameter('id');
            window.location.href = (currUrl + "&weekof=" + $('#datepicker').val());
            //console.log(currUrl + "&weekof=" + $('#datepicker').val());
        });

        //Populate the datepicker and make the instructions div visible
        if (!getUrlParameter('weekof')) {
            $('#instructions').show();
        } else {
            $('#datepicker').val(getUrlParameter('weekof'));
            $('#instructions').show();
        };
    });
</script>

<div display="hidden" id="instructions" class="hidden" aria-hidden="true">
    Select a Monday to compare: <input type="text" id="datepicker">
</div>

The end result: a little datepicker at the top of the report!

Screenshot of a date picker at the top of a report edit view.