DatePicker as Link Showing Date Value

Viewed 28

I would like to utilize bootstrap datepicker to style the date filters in a report, as shown below:

enter image description here

The HTML I'm using is:

<a href="javascript:;" class="badge badge-info datepicker filter_date_start_dp" data-date-format="mm/dd/yyyy"><i class="fal fa-filter" aria-hidden="true"></i> 11/1/2021</a>

The calendar is opening and selecting values does set the value correctly in the hidden input element.

The issues I'm experiencing are:

  1. The date is not appearing selected on first click.

  2. How can I transfer the selected date value to the text inside the anchor tag?

  3. The calendar is not closing.

  4. I'll need to refresh the page on selection.

I don't know how to handle #2 and #4 above since datePicker doesn't appear to emit any events.

I followed sage advice from this post but it doesn't appear to help:

how to show date picker on link click with jquery

There are all the same issues plus the datepicker shows up in the top left of the page.

1 Answers

This took a few hours but it's finally working. In case it helps anyone use datepicker from an anchor tag and force a page reload w/ the selected date as a parameter:

This goes in your $(document).ready(function () {:

    var dp_fields = obj.find('.dp');

    if (dp_fields) {

        dp_fields.each(function () {

            init_datepicker($(this));

        });

    }

This function should be defined somewhere as well:

    function init_datepicker (obj) {

        let date_start = obj.data('start-date');
        let reload = obj.data('reload');
        let url_param = obj.data('url-param');
        let target = obj.data('target');

        obj.datepicker({
            format: 'm/d/yyyy',
            defaultViewDate: date_start,
            autoclose: true,
            todayHighlight: true,
        }).bind('changeDate', function(date_obj) {

            let d = date_obj.date;

            if (date_obj) {

                if (d) {

                    let d2 = new Date(d);

                    let d_formatted = (`${ (d2.getMonth() + 1) }/${ d2.getDate() }/${ d2.getFullYear() }`);

                    $(target).val(d_formatted);
                    obj.find('.val').html(d_formatted);

                    if (reload) {

                        let url = new URL(window.location);

                        if (d_formatted) {

                            (url.searchParams.has(url_param) ? url.searchParams.set(url_param, d_formatted) : url.searchParams.append(url_param, d_formatted));

                        } else {

                            url.searchParams.delete(url_param);

                        }

                        window.location = url;

                    }

                }

            }

        });

    }
Related