jQuery Datepicker does not work in dynamic element

This always happen when bind the event initially, the new field doesn’t exist.
A better way is initialize the datepicker for the field when create the element.

Example after an AJAX call to build the fields:

//... ajax call here ....
//success function
success: function(data) {
	$('#report_fields').html(data);
	//initialize the datepicker for the field when create the element.
	$( "#from" ).datepicker({
		defaultDate: "-6m",
		changeMonth: true,
		numberOfMonths: 3,
		maxDate: 0,
		onSelect: function( selectedDate ) {
			$( "#to" ).datepicker( "option", "minDate", selectedDate );
		}
	});
	$( "#to" ).datepicker({
		defaultDate: null,
		changeMonth: true,
		numberOfMonths: 3,
		maxDate: 0,
		onSelect: function( selectedDate ) {
			$( "#from" ).datepicker( "option", "maxDate", selectedDate );
		}
	});
	//initialize date value
	var from = '<?php echo $from;?>';
	var to = '<?php echo $to;?>';
	if( from != '' ){
		$( "#from" ).val(from);
	}
	if( to != '' ){
		$( "#to" ).val(to);
	}
});

By Keenlio, August 5, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


− 3 = three

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>