I have a piece of code which inserts a link into a p tag when a date is selected from the datepicker.
For some reason the .click function of this dynamically created link does not work – but it does work if I hard code the button in exactly the same place rather than inserting it dynamically.
Any ideas why this is happening??
$(document).ready(function(){
$( "#MR1 > #datepicker" ).datepicker({
beforeShowDay: function(date){ return [(date.getDay() == 1 || date.getDay() == 4), ""] },
showOn: "button",
buttonText: "Book now...",
showWeek: true,
firstDay: 1,
onSelect: function(date) { $("#MR1 > #selecteddate").prepend("Date: " + $("#MR1 > #datepicker").val() + " - <a href='javascript:;' class='cleardate'>clear date</a>"); },
dateFormat: "DD, d MM, yy",
altField: "#datepickeralt",
altFormat: "dd/mm/yy",
navigationAsDateFormat: true,
minDate: 0,
});
$("#MR1 > #selecteddate > .cleardate").click(function(){
$("#MR1 > #selecteddate").html("");
$("#MR1 > #datepicker").datepicker("setDate", null);
$("#MR1 > #datepickeralt").val("");
});
});
body code as follows…
<div id="MR1">
<p id="selecteddate"></p>
<input type="text" id="datepicker" style="display:none;">
<input type="text" id="datepickeralt" disabled="disabled" style="display:none;">
</div>
You need to use the
.live()method instead.jQuery events work from the DOM generated at the page load, and thus any dynamically generated content after is ignored.
.live()uses thebodyelement as context and finds any matches for the selector you specified, thus maintaining the “bind” after the content has been added.I had a similar problem, it’s a fairly common question.