1

I just ran into a problem that stumped me for a while, and I don't see an SO question for it when I search, so I'm going to post it here to help folks who make the same (really dumb but hard to see) mistake. If nobody gets it in an hour, I'll post the answer.

What is my mistake?

  $('.myEndDate').each(new function (index) {
    $(this).datepicker(
      {
        changeMonth: true,
        numberOfMonths: 1,
        onClose: function (selectedDate) {
          $('.myStartDate').datepicker("option", "maxDate", selectedDate);
        }
      });
  });

The result is that firefox throws up this lovely error from inside the minified jqueryUI javascript:

TypeError: e.nodeName is undefined
http://localhost:8080/MyUI/scripts/jquery-ui-1.10.2.custom.min.js Line
1322

When I debug in firebug, it seems that this is

this    Object {}

It's possible I'm the only one who ever had trouble finding this mistake, and that's why I didn't find a question for it. Just in case someone else has a similar brain fart, maybe I can save them some time :)

Gus
  • 6,719
  • 6
  • 37
  • 58
  • 4
    Mmmm, why `new function`?? – elclanrs Mar 15 '13 at 00:42
  • 1
    why each ? , replace the selectors – Seder Mar 15 '13 at 00:45
  • ^ Yeah you don't need `each`, you can just call `datepicker` on the `.myEndDate` selector as a whole. – elclanrs Mar 15 '13 at 00:47
  • I am aware that I don't need each in this case. I've actually simplified the example from the original code. There was in fact other logic that added a css class with the index as a suffix so I could find it later with other code. But that's not important. – Gus Mar 15 '13 at 01:01

2 Answers2

4

The mistake is that by including the new keyword before the function declaration you're actually passing an empty object as the parameter to jQuery's each instead of a function for it to callback on each iteration. The result is, as you point out, that this refers to the empty object so the selector you use to instantiate the jQuery UI datePicker does not return a DOM node leading to the error you see in the console.

See this stackoverflow thread which explains that the construct you've used erroneously is a perfectly valid method of creating a new object in JavaScript, it just isn't any use to you in this instance.

Community
  • 1
  • 1
net.uk.sweet
  • 12,444
  • 2
  • 24
  • 42
1

You don't need to use each just use the selector for the datepicker

$('.myEndDate').datepicker(
  {
    changeMonth: true,
    numberOfMonths: 1,
    onClose: function (selectedDate) {
      $('.myStartDate').datepicker("option", "maxDate", selectedDate);
    }
  });

and when use each you don't need to say new function

I hope this can help :)

Seder
  • 2,735
  • 2
  • 22
  • 43