Reputation: 4583
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 :/
Upvotes: 1
Views: 7076
Reputation: 994
$(document).ready(function() {
$(".addSpan").click(function() {
var i = $("#dateTab input") .length + 1;
$("#dateTab").append($("<label>Date</label><input class='getDate id_"+ i +"' type='text' name='name[]' />"));
});
$( ".getDate" ).datepicker();
});
Upvotes: 0
Reputation: 86
Use .on() function for jquery 1.9+
$(document).on('click', '.datepicker', function(){
$(this).timePicker({
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd"
}).focus();
$(this).removeClass('datepicker');
});
Upvotes: 7
Reputation: 52799
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');
});
Upvotes: 1