I'm trying to add a calendar object using the datepicker as specified by JQuery tutorials. This is for an event form, and I need to add more events to select different event dates, so what I do is duplicate the elements within the form to reuse. This means the calendar input tag also gets duplicated. But, upon doing this, the calendar datepicker method will not call (or at least, it won't pop up the calendar). Why does this happen? I have the code right here:
<html>
<head>
<title>Calendar duplicate testing</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//jqueryui.com/resources/demos/style.css">
<script>
$(function() {
$( ".cal" ).datepicker();
});
function duplicateCalendar() {
var calendars = document.getElementsByClassName("calendarinstance");
var newcalendar = calendars[calendars.length - 1].cloneNode(true);
calendars[calendars.length - 1].appendChild(newcalendar);
}
</script>
</head>
<body>
<button type="button" onclick="duplicateCalendar();">Duplicate Calendar</button>
<br><br>
<div class="calendarinstance">
<img src="calendar.png" alt=""> Select Date: <input class="cal" type="text">
<br>
<hr>
<br>
<div>
</body>
</html>
You can see this code clicking here. I'm only putting the calendar object as it is the one thing that doesn't work. Thank you in advance for anyone's help!
Try this example.
The Script
We are using JQuery .clone(). Also, we need to attach “datepicker()” method with every new element. Read more about .clone() method.
The jQuery selector
$( ".cal" ).datepicker();
will only select the first instance of multiple classes of the same name.Take a look at .each() to reach all classes.
Call this function on duplicateCalendar() along with the existing code: