tags:

views:

295

answers:

2

Hi, i've got a problem, im loading into a div a page with form, that have date. I want to get there datepicker, but when the page is loaded with ajax, jquery doesn't see mine input. I tried something like this:

$('#birthdate').live('click', function() {
 $(this).datepicker({showOn:'focus'}).focus();
});

well it worked but the whole datepicker is blinking, sometimes doesn't show etc. Is there a possibility that ill show datepicker from mine own onlcik function? something like:

function choosedate() {
    $('#birhtdate').datepicker();
}

its not only with datepicker, i just don't know how to use jquery inside ajax loaded page.

+2  A: 

You should be able to call $("#yourdate").datepicker() when handling your ajax response.

For example:

$.get("new_div_contents.whatever", function(data) { 
  // do your thing with the data
  $("#yourdate").datepicker();
});
Andy Gaskell
A: 

I would separate the concerns into two components.

  1. Set up the datepicker for the input to be shown on focus
  2. Give the input focus when the page is updated.

Now if the input is updated via the AJAX call, you will need to reapply the datepicker whenever it is loaded. This is because any previous elements (being replaced) will be removed from the DOM along with the handlers for the datepicker. If not, then you only need to associate the datepicker with the input element once. Giving the element focus and triggering the focus event handlers should cause any associated datepicker to display.

$.get('/url/to/action', function(data) {
    $('#birthdate').datepicker( { showOn: 'focus' } );
     var bd = $('#birthdate').focus().get(0);
     if (bd) bd.focus();
});

Note that the jQuery documentation is unclear on whether calling focus() on the jQuery object actually gives focus to the element or simply invokes the focus event handlers. The code above assumes that it doesn't give the element focus and so that is done using the javascript method. This may not be necessary, but I haven't tried it and am depending on the (conflicting) documentation.

tvanfosson