views:

49

answers:

1

I have a function that attaches the jQuery UI DatePicker (with my options) to a passed jQuery object:

function bindDatepicker($obj)
{
  if ($obj == null) $obj = $("input.date");

  $obj.datepicker(
    { 
      appendText: '(yyyy-mm-dd)',
      autoSize: true,
      changeMonth: true, 
      changeYear: true, 
      closeText: 'Done',
      dateFormat: 'yy-mm-dd',
      defaultDate: '+1m', 
      minDate: +1, 
      numberOfMonths: 2
    }
  );
}

I call this at the beginning of every page to bind it to input elements:

$(function() {
  bindDatepicker($("input.date"));
});

This works fine. My problem comes in when I load form elements using $.load(). I cannot attach the DatePicker to any of the loaded elements. For example:

$("#id").load("urlToLoad", function() {
    bindDatepicker($("input.date"));
});

Loads the form elements into a div just fine, but will not attach the DatePicker.

Why is this? I am stumped. :(

Thanks, Tom

+2  A: 

You need to use the jQuery .live() method. It will "listen" for any new elements that match your selector criteria.

EDIT: So my original answer was wrong. The .live() method is only for binding events. As you have pointed out in your comments you can't actually bind to an event if there's no event to bind to. So I decided to whip up a sample and see if I could reproduce your problem and I could. What was weirder tho, was if I tried to use an attribute based selector, rather than a class selector, it worked perfectly.

So instead of doing

$('input.date').datepicker();

I stuck a new attribute on there called 'type' and had the following selector:

$('[type=date]').datepicker();

and everything worked.

I have no idea why this is but I can only assume it's a bug with jQuery.

lomaxx
Can you please elaborate? I attempted to use the $.live() function, but what event would you bind this to? Please help me to understand: Once the elements are loaded using $.load(), they exist in the DOM, right? The callback function should then be triggered and the selector would traverse the DOM for all "input.date" elements, right? Please tell me if I am misled here... Thanks!
TomWilsonFL