longbill / jquery-date-range-picker

A jQuery plugin that allows user to select a date range
MIT License
1.12k stars 579 forks source link

Uncaught TypeError: Cannot read property 'find' of undefined #470

Closed sogrbilja closed 5 years ago

sogrbilja commented 5 years ago

This is maybe trivial to you, but I am facing a strange problem, I am using this function to set dateRangePicker to a control and to set it's value.

   function SetDateTime(controls, value, DateTimeFormat) {
      $(controls).dateRangePicker({
        autoClose: true,
        singleDate: true,
        showShortcuts: false,
        singleMonth: true,
        time: {
          enabled: DateTimeFormat === globalDateFormat ? false : true
        },
        format: DateTimeFormat
      });
      if (value) {
        $(controls).data('dateRangePicker').setStart(moment(value).toDate());
      }
      $('.date-picker-wrapper').css("z-index", 3);
    }

On a page I have a dynatable, so when a user select a value from the dynatable it shows input fields with dateRangePicker included, but when user clicks on an another record it stops on $(controls).data('dateRangePicker').setStart(moment(value).toDate()); line saying "Uncaught TypeError: Cannot read property 'find' of undefined". I have noticed, also, that if I click on all fields and invoke calendar drop down I can click on the next row to and display it without error. Errors come also when I resize browser window, I mean why it needs to listen to window resize if calendar is not yet shown?

How this can happen?

Thanks, Dejan

sogrbilja commented 5 years ago

OK, I found the problem I had to rewrite my function like this:

    function SetDateTime(controls, value, DateTimeFormat) {
      if (typeof $(controls).data('dateRangePicker') === 'undefined')
        $(controls).dateRangePicker({
          autoClose: true,
          singleDate: true,
          showShortcuts: false,
          singleMonth: true,
          time: {
            enabled: DateTimeFormat === globalDateFormat ? false : true
          },
          format: DateTimeFormat
        });
      if (value)
        $(controls).data('dateRangePicker').setStart(moment(value).toDate());
      else
        $(controls).data('dateRangePicker').clear();
      $('.date-picker-wrapper').css("z-index", 3);
    }

The main thing is that I had to avoid another initialization when the control's daterangepicker is already initialized.