Search code examples
javascriptjqueryasp.netjquery-ui-datepickerjquery-events

Selecting date in datepicker fires wrong event


I have two elements on my website:

<asp:DropDownList CssClass="SelectionDDL" ID="ddlClientMapFilter" runat="server"></asp:DropDownList>

and somewhere else on the page:

<asp:TextBox ID="tbFromDate" runat="server" OnTextChanged="ddl_ReportFilterChanged"></asp:TextBox>
<asp:TextBox ID="tbToDate" runat="server" OnTextChanged="ddl_ReportFilterChanged"></asp:TextBox>

In Javascript in:

$(function(){
    $(document).on("change", $("#ddlClientMapFilter"), function() {
         RefreshMapList();
    });
});

and somewhere else on page in: Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(OnAsychPostback);

function OnAsychPostback(s, e) {
$("#tbFromDate").datepicker({
            defaultDate: "-1",
            changeMonth: true,
            numberOfMonths: 3,
            onClose: function (selectedDate) {
                $("#tbToDate").datepicker("option", "minDate", selectedDate);
            }
        });
        $("#tbToDate").datepicker({
            //defaultDate: "+1w",
            changeMonth: true,
            numberOfMonths: 3,
            onClose: function (selectedDate) {
                $("#tbFromDate").datepicker("option", "maxDate", selectedDate);
            }
        });
}

Now the strange part.

Everything seems to be working except that every time I select a date using any of the datepickers the dropdown event gets fired. I know the solution is simple add if and check were there the target of the event is that dropdown but I'd like to know how to not fire that event, also I have tons of other events attached next to that one and only this one is fired.

Apparently there is a bug somewhere but I don't know how to find it any ideas?


Solution

  • it is because the second argument to on()(in delegation syntax) must be a selector string, not a jQuery object

    $(function(){
        $(document).on("change", "#ddlClientMapFilter", function() {
             RefreshMapList();
        });
    });
    

    Demo: Fiddle

    In the demo the first handler is fired only when the #x element is changed, but the second handler is fired when any input is changed.

    The root cause seems to be that if the second argument is not a string, then it is considered as the data parameter(you can check the data property of the event object to test this)...

    Demo: Fiddle