JazzCat JazzCat - 1 year ago 134
jQuery Question

jQuery datepicker appended not working

I have this problem when im trying to display a number of fields, and onclick on those datepicker is supposed to run, if i put the code outside the javascript it works just fine, so there must be something wrong with how i $.each loop it or with the append, but somehow im not getting it to work.

$(function() {

$(".datepicker").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd"
});

var val = [];

$(':checkbox:checked').each(function(i){

val[i] = $(this).attr("id");

});


if(val == "")
{

alert('no selection');

}
else
{

$.post("add_stuff", { "post" : val, "csrf" : cct },
function(data)
{
$("#content").empty();

json = eval('('+data+')');

$.each(json.datecheck, function() {
$("#content").append("<h2>" + this.pName + " - " + this.pDesc + "</h2>");
$("#content").append("<p>Datum: <input type='text' class='datepicker'></p>");
});


});


}
});


The post -> runs insert query in controller, and returns some json data thats looped out.
And for each row that's returned i want a inputfield , a working one :)
Would really appreciate some help, been struggling with this way too long now :/

Answer Source

The current binding will not work as the element does not exist.
As the addition of the the input field is dynamic, you would need to use JQuery live

Example -

$('.datepicker').live('click', function(){
    $(this).timePicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd"
    }).focus();
    $(this).removeClass('datepicker');
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download