Reputation: 7115
I have Javascript code for date picker like this:
$(document).ready(function(){
$("#date").Datepicker({
Field: '#date',
Format: "YYYY/MM/DD",
date: true,
format: 'YYYY/MM/DD'
});
});
Date element works correctly. But when I edit my post, I create date element with AJAX. When I click date element again, the datepicker does not work and also does not show any error to me.
AJAX code :
$(document).on("click", ".edit-btn", function () {
$.ajax({
type: 'put',
url: 'edit',
data: $(".form").serialize(),
success: function (result) {
$('#ajax_div').html(result);
}
})
})
Upvotes: 1
Views: 471
Reputation: 25807
You need to recall your date picker code after you dynamically append the HTML code. To fix this, put the code in a function:
function enableDatePicker() {
$("#date").Datepicker({
Field: '#date',
Format: "YYYY/MM/DD",
date: true,
format: 'YYYY/MM/DD'
});
}
Call it immediatly:
$(document).ready(function(){
enableDatePicker();
});
And call also after you appended the HTML:
$(document).on("click", ".edit-btn", function () {
$.ajax({
type: 'put',
url: 'edit',
data: $(".form").serialize(),
success: function (result) {
$('#ajax_div').html(result);
enableDatePicker(); // Call it again
},
})
});
Also, the another problem I see is that you are calling .Datepicker()
on an element with an id date
which is stating that there can only be a one element with that id
(as an HTML dom should have id
unique). So try to use a class selector and then call the .Datepicker()
on that.
Upvotes: 1
Reputation: 32354
Try this code:
$('body').on('focus',"#date", function(){
$(this).datepicker({
date: true,
format: 'YYYY/MM/DD'
});
});
Upvotes: 1
Reputation: 1675
It doen't work because your document is already complete. AJAX is loaded after that.
You could use
$( document ).ajaxComplete()
see here the full doc: http://api.jquery.com/ajaxcomplete/
PS. i never used it i just found out about it.
it should be like this:
$(document).ajaxComplete(function(){
$("#date").Datepicker({
Field: '#date',
Format: "YYYY/MM/DD",
date: true,
format: 'YYYY/MM/DD'
});
});
Upvotes: 3