Getting jQuery datepicker live, when html is loaded from ajax - jquery-ui

I have the following jQuery script defined on all my forms.
$( "input:text.datepicker" ).datepicker({
yearRange: "1900:+0",
changeMonth: true,
changeYear: true
});
Basically this invokes the date picker on any input element that is of type text and has the class "datepicker".
This works fine on all pages, except in one situation which I describe below.
I have to load a form by ajax, which is then displayed in a jQueryUI Dialog. In this dialog I can only get the date picker to display if I include the java-script code again. Obviously I don't want to include the code twice. Is there a way to get the newly loaded textbox to display the date picker somehow?
Thank you

One option is to use on method in deprecated live way and click event to initialize Datepicker:
$('body').on('click', 'input.datepicker', function(event) {
$(this).datepicker({
showOn: 'focus',
yearRange: '1900:+0',
changeMonth: true,
changeYear: true
}).focus();
});
This code should be placed in $(document).ready section.
Pay attention to showOn: 'focus' option and triggering focus event after initialization.
DEMO: http://jsfiddle.net/Mq93s/

Well the problem here is that when the datepicker code is executed, your form element does not exist yet, and therefore, it cannot convert it to a datepicker. You could bypass this problem by either:
Moving the datepicker code to a separate function that you will then call manually from all pages in the document.ready event. This way it will only be declared once, and you can also call it in your ajax page as well, only there you will call it when the ajax call is completed instead of the ready event.
Since you know what you're loading in your form, you can convert just that given input to a datepicker. This is not such a clean solution, because if you will want to change something in the datepicker, you'll have two places to modify, at least.
Both approaches are valid, the choice is up to you, as you know which version fits your project better :)

Related

Always Display jQuery UI Date Picker on Input

I need to set up two jQuery UI date pickers to always be displayed. I know there's an easy way to do this with DIVs, but I can't find anything on how to do it for inputs. I've tried the "show" method in the jQuery UI documentation, but that just acts as a click on the input on page load, which isn't what I'm looking for.
I just tested the code below and it always remains on the page. You will need to handle the selection/click events by passing options the datepicker in the javascript. I added the JS for when the user selects a date... that should give you enough to go off of.
HTML:
<div id="test"></div>
<input type="text" id="date_input">
Javascript:
$('#test').datepicker({
onSelect: function(date, obj){
$('#date_input').val(date); //Updates value of of your input
}
});

JQuery UI Datepicker currently displayed months

Im using datepicker in div with this configuration"
$("#homeDatepicker").datepicker({
numberOfMonths: 3,
dateFormat: 'dd-mm-yyyy',
firstDay: '1'
...
});
how do i know which monts are currently displayed in div (user can navigate to display next and previous one).
i want to load some external data using ajax depending on this data.
As indicated in this link http://jqueryui.com/datepicker/#multiple-calendars
The current month based on today's date and followed by next two months are displayed.

Datepicker doesn't display the date on the text after an ajax call

I have a div ided as inPatientDecision, the contents for which are loaded dynamically through an Ajax call. The loaded content has a few HTML datepicker elements with class attribute set to datePicker. To instantiate the Jquery UI Datepicker calendar to those elements, I've set $(\'.datePicker\').datePicker(); on ajax complete. The ajax call is:
jQuery.ajax({type:'POST',
data:{'inpatientDecisionId': '6'},
url:'/myproje/um/editDecision/13',
success:function(data,textStatus){
jQuery('#inPatientDecision').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){},
complete:function(XMLHttpRequest,textStatus){
$(\'.datePicker\').datepicker();
}});;
alt="Edit Authorization Decision" src="/everest/images/edit_icon.png">
Now when the content loads and the datepicker element is clicked, I sure can get the calendar displayed. But when I select any date, the selected date is not displayed to the input boxes.
Sure something like this has been asked here before but the solutions provided haven't been much helpful to me (possibly neither to the previous OP, an answer hasn't been accepted).
Please see my updated code below
jQuery.ajax({type:'POST',
data:{'inpatientDecisionId': '6'},
url:'/myproje/um/editDecision/13',
success:function(data,textStatus){
jQuery('#inPatientDecision').html(data);
$(\'.datePicker\').datepicker();
},
error:function(XMLHttpRequest,textStatus,errorThrown){},
});;
Basically complete and success would execute together, so i just placed datepicker after you place html in success section.
Hopefully this should work.

JqueryMobile page initialization function

I am using a master page on a JQuery-Mobile app that have few controller , and I want to set up a Javascript call to an initialize function on every page even when it loads through Ajax,
Iam sure there are few ways to do that, but whats the best approach and what would be the alternative to $(document).ready when the page is called through ajax instead of being directly loaded without that.
takepara's answer is correct, but...
If you want to modify the content of the page you will have to bind earlier.
Take a look at beforepagecreate event.
If your handler for this event returns false, then no JQM widgets and styles will be applied and you can work with it manually.
jQuery Mobile Docs - Events
$('div').live('pageshow',function(event, ui){
alert('This page was just hidden: '+ ui.prevPage);
});
or
$(document).bind("pageshow".function(){
// initialize code here
});

Why does jQuery UI's datepicker break with a dynamic DOM?

I'm working with a dynamic DOM here, and have called the jQuery UI datepicker to all inputs with a specific class name, in this case .date
It works great with the first, static, construct but when I clone it the event handlers don't seem to want to move over. I get the Firebug error:
inst is undefined
I tried looking into jQuery's new live() function but couldn't combine the two. Any ideas?
Ah, got it. Right after I append the HTML to the DOM I run this on all the inputs I'd like to have a datepicker pop up with. Datepicker adds a class to elements it has been attached to, so we can filter out existing inputs and only apply it to new ones.
$('.date').not('.hasDatePicker').datepicker();
I hope this helps people as I was Googling for days and didn't find anything!
You should also note that it would be faster to check for input.date in the new generated HTML by setting that as a context, rather than the whole page, as it will save time, due to this being a more efficient operation.
I had a similar Issue, I had multiple tables on a page and each had multiple datepickers, also on click of button "AddLine" it added a table row with dynamic HTML and datepicker.
I realized after a lot of search that my input date fields had no "id" defined they looked like this
<input type="text" class="datepicker" name="mDate1" value="" size=8 >
jquery was pointing all the date fields values to the very first date field defined on page, the calendar would popup on all the date fields but the value of 1st date field would change, I made a change to the html like this
<input type="text" class="datepicker" id="Date1" name="mDate1" value="" size=8 >
by adding a "id" and it started working, for the dynamic date fields I change the Id like this
var allColumns = $("#"+$tableId+" tr:last td");
$(allColumns).each(function (i,val) {
if($(val).find(":input").hasClass("datepicker")){
$(val).find(":input").attr("id",newId+$(val).find(":input").attr("id"));
}
});
You need to use the 'live' event to make it work with dynamic DOM. So, if the class for your datepicker inputs is 'date-input', following code will make it work:
$(document).ready(function() {
$('.date-input').live('click', function() {
$(this).datepicker('destroy').datepicker({showOn:'focus'}).focus();
});
});
This might be a little late, but all the suggestions above didn't work for me, I came up with an easy solution for this.
First, what is causing the problem:
JQuery assign datepicker to element id. if you are cloning element, then same id might be cloned as well. which jQuery doesn't like. You might end up with either receiving null reference error or the date being assigned to first input field regardless which input field you click on.
Solution:
1) destroy datepicker
2) assign new unique ids to all input field
3) assign datepicker for each input
Make sure your input is something like this
<input type="text" name="ndate[]" id="date1" class="n1datepicker">
Before you clone, destroy datepicker
$('.n1datepicker').datepicker('destroy');
After you clone, add these lines as well
var i = 0;
$('.n1datepicker').each(function () {
$(this).attr("id",'date' + i).datepicker();
i++;
});
and the magic happens
Use
$j(id or class).removeClass('hasDatepicker').datepicker();
It is working
Use jQuery selectors:
$(".mydatepicker:not(.hasDatepicker)").datepicker()
Multiple instances of the jquery-ui library on the page will cause this error too. Removing redundant instances work for my case
I experienced the same symptom, in this caused by having a td containing element with the same id attribute as the input,
<td id="fld_xyz"><input id="fld_xyz" class="date" /></td>
I know this isn't ideal anyway, but it's worth knowing that the datepicker component seems to be relying on the uniqueness of the id.
I had this problem. My situation ended up being I had another element with the same ID as the input with the datepicker.
Today I faced the same issue... I am using datetimepicker plugin in my application.
Also using jquery's default datepicker too. When ever I am invoking them both on document ready I am getting the error inst is undefined.
$(document).ready(function(){
$(".datepickerCustom").datetimepicker();
$(".datepicker").datepicker();
$("#MainForm").validationEngine('attach');
....
});
So I changed the code to invoke before document ready like below:
$(".datepickerCustom").datetimepicker();
$(".datepicker").datepicker();
$(document).ready(function(){
$("#MainForm").validationEngine('attach');
....
});
Now every thing is working fine. No problems.
I had a similar problem with data picker not working after a first call. I found an answer to my issue here:
http://www.stemkoski.com/problem-with-jquery-ui-datepicker-dynamic-dom/
I was cloning sections dynamically from template and inadvertently including the class that datepicker adds once its called:
hasDatepicker
I placed my first datepicker call after I clone the template and that did it. I then added a datepicker call after each instance of clone:
$(source).clone().appendTo(destination).find(".datepicker").datepicker();
After trying many of the answers here, this is what worked for me and is showing on the first click/focus
function vincularDatePickers() {
$('.mostrar_calendario').live('click', function () {
$(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
});
}
this needs that your input have the class 'mostrar_calendario'
live is for JQuery 1.3+ for newer versions you need to adapt this to "on"
See more about the difference here http://api.jquery.com/live/
If it still doesn't work, it is because of the cloned id. You can completely remove datepicker like this:
$(selector).removeClass('hasDatepicker').removeAttr('id').datepicker();

Resources