Home > other >  How to call function after change rather than on change
How to call function after change rather than on change

Time:09-17

I am building a dashboard page that needs to allow a user to select a date range and update the statistics based on the selection. The current issue I'm running into is how to call a function after the second date is selected without having the user press a button to update the stats.

HTML

<div  style="display: none; margin: 0; border: none;">
  <label for="from_date_picker">From:</label>
  <input type="text" id="from_date_picker"  onchange="filterDate()">
  <label for="to_date_picker">To:</label>
  <input type="text" id="to_date_picker"  onclick="filterDate()" onchange="selectCampaign()">
</div>

Functions to set jquery datepicker and default/min dates

<script>
    // This function grabs the date from the "FROM" input and sets it as the minimum date so that the user can't select a date befor the "FROM" date
    function filterDate() {
        $("#to_date_picker").datepicker({
            minDate : $("#from_date_picker").datepicker('getDate'),
            defaultDate : "{{datetime.date}}"
        })
    }
</script>


<script>
    $(function() {
        $( "#from_date_picker" ).datepicker({
            defaultDate:"{{datetime.date}}"
        });
    });
</script>

Select Campaign Function *there are multiple filter options, I'm currently only worried about the last one that populates the date selection inputs

<script>
    function selectCampaign(){


        var selected = $('#filter-selector').find(":selected").index()

        if (selected == 0) {
            ...
        }

        else if (selected == 1) {
            fromDate = $('#from_date_picker').datepicker('getDate')
            toDate = $('#to_date_picker').datepicker('getDate')

            alert(fromDate, toDate)
        }
    }
</script>

Currently, these alerts only show the date for the "FROM" input because the "TO" option is not actually selected until after the function fires. I want to know how I can delay the function call to occur after the date selection is finished. I want to do this without having the user click a button so that the dashboard has a more dynamic field. How can I accomplish this?

Select From date:

From Selection

Select To date:

To Selection

Alert only shows the first date selection:

Alert

CodePudding user response:

instead of the inline onChange event listener, use the built-in onSelect that ships with the datepicker component

$("#to_date_picker").datepicker({
  minDate: $("#from_date_picker").datepicker('getDate'),
  defaultDate: "{{datetime.date}}",
  onSelect: function(dateText) {
    console.log("Selected date: "   dateText   "; input's current value: "   this.value);
    selectCampaign()
  }
})
  • Related